Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, Get result from third activity

In first activity, there is empty ListView and Button.

When I press button, it starts second activity that has ListView of categories.

After I click into one of listElements it will start third activity that has ListView with elements that are belong to my chosen category.

When I choose element of third ListView it must send me back to first activity, where my chosen element is added to my empty ListView

like image 690
zxcdsa980 Avatar asked Mar 09 '15 14:03

zxcdsa980


Video Answer


2 Answers

Use Intent.FLAG_ACTIVITY_FORWARD_RESULT like this:


FirstActivity should start SecondActivity using startActivityForResult().

SecondActivity should start ThirdActivity using this:

Intent intent = new Intent(this, ThirdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(intent);
finish();

This tells ThirdActivity that it should return a result to FirstActivity.

ThirdActivity should return the result using

setResult(RESULT_OK, data);
finish();

At that point, FirstActivity.onActivityResult() will be called with the data returned from ThirdActivity.

like image 177
David Wasser Avatar answered Nov 09 '22 07:11

David Wasser


Though I'd implore you to change your architecture design, it is possible to do it like this:

File ActivityOne.java

...
startActivityForResult(new Intent(this, ActivityTwo.class), 2);
...
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == RESULT_OK && data != null) {
        //Collect extras from the 'data' object
    }
}
...

File ActivityTwo.java

...
startActivityForResult(new Intent(this, ActivityTwo.class), 3);
...
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == RESULT_OK && data != null) {
        setResult(resultCode, data);
        finish();
    }
    setResult(RESULT_CANCELLED);
}
...

File ActivityThree.java

...
//Fill the Intent resultData with the data you need in the first activity
setResult(RESULT_OK, resultData);
finish();
...
like image 27
nstosic Avatar answered Nov 09 '22 09:11

nstosic