StartActivityForResult resultcode is always 0
I am trying to get an edited list from activity 2 to activity 1. Here is my code:
public void listDataSms(ArrayList<MySmsLog> stringList) {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(NUMBER_LIST, stringList);
Intent i = new Intent(this, MyCommonListActivity.class);
i.putExtra(WHO_INT, SMS_LOG);
i.putExtras(bundle);
startActivityForResult(i, SMS_LOG);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SMS_LOG) {
if (resultCode == RESULT_OK) {
ArrayList<MySmsLog> mySmsLogs = (data.getParcelableArrayListExtra(PICK_SMS_LOG));
mainLog.setSmsLog(mySmsLogs);
}
if (resultCode == RESULT_CANCELED) {
// do something if there is no result
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
Bundle result = new Bundle();
switch (who) {
case SMS_LOG:
result.putParcelableArrayList(MainActivity.PICK_SMS_LOG, mySmsLogList);
break;
}
setResult(RESULT_OK, intent);
intent.putExtras(result);
}
But I never get setSmsLog
, because resultCode
always 0
. I tried Android's onActivityResult always 0 but no result. Even if I change my state to if (resultCode == RESULT_CANCELED) {do smth}
, the program ends with NullPointerException
.
source to share
Assuming onBackPressed()
from your above code from MyCommonListActivity
, it's too late to call setResult()
. At its best, your code can work if you call super.onBackPressed()
as the latter, not the first. A typical solution is to invoke setResult()
and finish()
as soon as the user clicks something in ListView
or otherwise selects a specific item to work with, rather than waiting for the user to hit BACK.
source to share