Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get back the result from Child activity to Parent in android?

I'am starting a child activity on click of a button from Parent. And i'am calculating some result (of type string) in child activity and finishing the child to come back to Parent. Is there any better way to get that result in Parent using intents or extras? (I can get that result in Parent by making the result variable as public & static in Child) Please help me. I'am a newbie to android development.

startActivityForResult(new Intent(ParentActivity.this, ChildActivity.class), ACTIVITY_CONSTANT);

What should i write in onActivityResult() of Parent?

like image 234
SANDHYA Avatar asked May 14 '12 11:05

SANDHYA


1 Answers

Instead of startActivityForResult(new Intent(ParentActivity.this, ChildActivity.class), ACTIVITY_CONSTANT);

You can use putExtras() method to pass values between activities:

In Child Activity:

Intent data = new Intent();
data.putExtra("myData1", "Data 1 value");
data.putExtra("myData2", "Data 2 value");
// Activity finished ok, return the data
setResult(RESULT_OK, data);
finish();

And in Parent activity, you can override onActivityResult() and inside that you can have Intent paramater and from the Intent parameter of this method you can retrieve the extra values passed from the child activity, such as intent.getStringExtra or intent.getSerializableExtra.

for example:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
        if (data.hasExtra("myData1")) {
            Toast.makeText(this, data.getExtras().getString("myData1"),
                Toast.LENGTH_SHORT).show();
        }
    }
}
like image 171
Paresh Mayani Avatar answered Oct 18 '22 18:10

Paresh Mayani