简体   繁体   中英

startActivityForResult resultcode always 0

I'm trying to get edited list back 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 is always 0 . I tried Android onActivityResult is always 0 this but with no result. Even if I change my condition to if (resultCode == RESULT_CANCELED) {do smth} program ends with NullPointerException .

Assuming that onBackPressed() from your code shown above is from MyCommonListActivity , that is too late to call setResult() . At best, your code might work if you call super.onBackPressed() as the last thing, not the first. The typical solution is to call setResult() and finish() as soon as the user taps on something in a ListView or otherwise chooses the particular item to work with, rather than wait until the user presses BACK.

Try to put super.onBackPressed(); after intent.putExtras(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM