3

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.

Community
  • 1
  • 1
previ
  • 87
  • 1
  • 7

2 Answers2

7

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 2
    I moved with that super.onBackPressed() and it´s working now! I know that using BACK is not so good solution, but unfortunately i need it in this example. Thank you! Just one more question, why should be super.onBackPressed() last thing in my method? – previ Apr 25 '15 at 17:11
  • @previ: You need to call `setResult()` before `finish()`. The default behavior of `onBackPressed()` calls `finish()`. Hence, your call to `super.onBackPressed()` calls `finish()`, and you need to do `setResult()` before that. – CommonsWare Apr 25 '15 at 17:16
1

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

Andrew
  • 36,676
  • 11
  • 141
  • 113