Like Getting a result from another Activity you need to call the Fragment
's method startActivityForResult(Intent intent, int requestCode)
. note that you should not call getActivity().startActivityForResult()
as this will take the result back to the Fragment
's parent Activity
.
Receiving the result can be done using the Fragment
's method onActivityResult()
. You need to make sure that the Fragment's parent Activity also overrides onActivityResult()
and calls it's super
implementation.
In the following example ActivityOne
contains FragmentOne
, which will start ActivityTwo
and expect a result from it.
ActivityOne
public class ActivityOne extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
}
// You must override this method as the second Activity will always send its results to this Activity and then to the Fragment
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
activity_one.xml
<fragment android:name="com.example.FragmentOne"
android:id="@+id/fragment_one"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FragmentOne
public class FragmentOne extends Fragment {
public static final int REQUEST_CODE = 11;
public static final int RESULT_CODE = 12;
public static final String EXTRA_KEY_TEST = "testKey";
// Initializing and starting the second Activity
private void startSecondActivity() {
Intent intent = new Intent(getActivity(), ActivityTwo.class);
startActivityForResult(REQUEST_CODE, intent);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
String testResult = data.getStringExtra(EXTRA_KEY_TEST);
// TODO: Do something with your extra data
}
}
}
ActivityTwo
public class ActivityTwo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
}
private void closeActivity() {
Intent intent = new Intent();
intent.putExtra(FragmentOne.EXTRA_KEY_TEST, "Testing passing data back to ActivityOne");
setResult(FragmentOne.RESULT_CODE, intent); // You can also send result without any data using setResult(int resultCode)
finish();
}
}