Reputation: 41
I have Fragment A hosted by Activity A and Fragment B hosted by Activity B. Fragment A calls Activity B. I want to send data back to Fragment B to Fragment A. I tried overriding setResult
but it didn't work.
Upvotes: 0
Views: 61
Reputation: 522
Use https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html then anything that needs to know what happened can register a receiver for it.
Upvotes: 0
Reputation: 711
From your FragmentA
call the ActivityB
using startActivityForResult() method
For example:
Intent i = new Intent(getActivity(), ActivityB.class);
startActivityForResult(i, 12345);
In your ActivityB set the data which you want to return back to ActivityA. If you don't want to return back, don't set any.
For example: In ActivityB if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your FragmentA class write following code for the onActivityResult() method.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
Upvotes: 1