startActivityForResult for three activities

2.2k views Asked by At

I have three activities : A , B, C. My application flow is : A -> B & B->A or A -> B & B ->C & C->A. So i used startActivityForResult to pass data from A to another activities and in A i also have onActivityResult to handle received data. In B, I change data and go to C by:

Intent intent = new Intent(this,C.class);
Bundle bundle = this.getIntent().getExtras();
bundle.putSerializable("newdatafromA", newdatafromA);
intent.putExtras(bundle);
startActivity(intent);

In C, I get data and change something. I try to setResult() with result code and go to A but it not success:

Intent positveActivity = new Intent(getApplicationContext(),A.class);
Bundle bundle = new Bundle();
bundle.putSerializable("newdata", newdata);
bundle.putSerializable("newdatafromA", newdatafromA);
positveActivity.putExtra("data", bundle);
setResult(2, positveActivity);
startActivity(positveActivity);

I debug and it dont jump to onActivityResult(I handle result code =2 in here) in A.class. and bundle have all data. Any idea to help me resolve it ?

3

There are 3 answers

3
Abdul Mohsin On BEST ANSWER

From your Activity B. When you are going to Activity C. then use startActivityForResult then in Your Activity B. override onActivityResult and handle the Data came from Activity C. then pass the data back to Activity A by setResult just you did in activity C. So this Data will be passed back to Activity A

Flow:

Activity A --> Activity B --> Activity C then back from Activity C --> Activity B and finally back to Activity A

0
Makwana On

to get back to OnactivityResult you should not create an intent and then startActivity A..

You just have to call finish(); method and will automatically return to Activity A and run onActivityResult ...

Like : in Activity C:

Bundle bundle = new Bundle();
bundle.putSerializable("newdata", newdata);
bundle.putSerializable("newdatafromA", newdatafromA);
positveActivity.putExtra("data", bundle);
setResult(2, positveActivity);
finish();

Hope it helps :)

0
Darpan On

When you start Activity A from activity C, start using normal method only but -

Use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP as your flag. Then it will work the way you desire.

 Intent intent = new Intent(C.this,A.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

Source here