Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning intent result when Activity is closed by back button

I start a new Activity from the original Activity with startActivityForResult(intent, requestCode). I want to return data to the original Activity when the user presses the back button, so when returns to the original Activity. I tried two methods:

  • overriding onBackPressed():

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    
        Intent intent = new Intent();
        intent.putIntegerArrayListExtra(SELECTION_LIST, selected);
        setResult(RESULT_OK, intent);
    }
    
  • overriding onPause():

    @Override
    protected void onPause() {
        super.onPause();
    
        Intent intent = new Intent();
        intent.putIntegerArrayListExtra(SELECTION_LIST, selected);
        setResult(RESULT_OK, intent);
    }
    

Unfortunately, none of them worked (resultCode is not RESULT_OK in onActivityResult()). What's the proper way to do this? Thanks!

like image 331
WonderCsabo Avatar asked Jan 02 '13 11:01

WonderCsabo


People also ask

How do I go back on activity intent?

You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.

What is taskaffinity in Android?

An affinity indicates which task an activity prefers to belong to. By default, all the activities from the same app have an affinity for each other. So, by default, all activities in the same app prefer to be in the same task. However, you can modify the default affinity for an activity.

What is intent FLAG_ activity_ new_ task?

FLAG_ACTIVITY_NEW_TASK is equivalent to launchMode=singleTask and in there I read. However, if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance.


1 Answers

Try this :

@Override
public void onBackPressed() {
   // super.onBackPressed();

    Intent intent = new Intent();
    intent.putIntegerArrayListExtra(SELECTION_LIST, selected);
    setResult(RESULT_OK, intent);
    finish();
}
like image 59
Pratik Sharma Avatar answered Sep 19 '22 22:09

Pratik Sharma