Tarcisiofl Tarcisiofl - 1 year ago 93
Android Question

How to go back from one Activity to one Fragment?

I have a Main Activity that extends to AppCompatActivity, which contains a FrameLayout and I used to replace it with the desire Fragment.

However, at one time, I called another activity only to show up some specific information, and need to pass back that information to the Main Activity with the last Fragment showed. Thus, I tried to use FragmentManager, and the Fragment shows transparent; also, if I used that, I lost the Main Activity's FrameLayout id.

To try to clarify, I will put a scheme:


Is possible to use onBackPressed to solve it?


Below is my onActivityResult that calls startActivityForResult, which is used in a Fragment.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == 2) {
if (resultCode == Activity.RESULT_OK) {

execusaoVistoria.fotos = allFotos;

Intent startPreview = new Intent(getContext(), PreviewActivity.class);
startPreview.putExtra("path", fileName.toString());
startPreview.putExtra("ExecusaoVistoria", execusaoVistoria);
startActivityForResult(startPreview, 10);

} else if (requestCode == 10) {

if (resultCode == Activity.RESULT_OK) {

allFotos.add((Fotos) data.getBundleExtra("Bundle").getParcelable("foto"));



And here, is the code from the Activity that calls the setResult:

Intent i = new Intent();
i.putExtra("Bundle", bundle);
setResult(Activity.RESULT_OK, i);

Answer Source

You should use startActivityForResult instead of startActivity.

In your MainActivity you will receive a callback


here you can fetch the info you need.

How to manage `startActivityForResult` on Android?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download