0

What I am attempting is to wait in my main activity until my fragment finishes, so I can execute code without causing problems in the fragment. I have tried many methods and can't get a solution. Heres some of my code from my main activity:

if (null == savedInstanceState) {

        getFragmentManager().beginTransaction()
                .replace(R.id.container, CameraFragment.newInstance())
                .commit();
    }

This will run a fragment that takes a picture and saves it.

The problem i'm having is, for example, I want to wait until this fragment has finished, then execute more code from my main activity. I can't find a working solution.

Edit: Solved, see the answer. Thanks!

2 Answers2

3
  • Create a method on your activity, to run when your fragment is complete
  • Implement the OnResume method on the fragment like this:



@Override
public void onResume() {
    super.onResume();
    ((NameOfActivity) getActivity()).afterFragmentComplete();
}

Jordan Junior
  • 1,090
  • 10
  • 11
  • If I'm understanding correctly, this code goes inside my fragment, and I want to execute code from my main activity, not from my fragment. – OxenFreeHorchata Mar 22 '16 at 20:14
  • This code will be on your fragment, but it will call a code from your main activity, just after the fragment is complete. The main activity will wait until the fragment complete and run the "afterFragmentComplete()" that will stay on the MainActivity – Jordan Junior Mar 22 '16 at 20:33
  • I implemented this, and it runs afterFragmentComplete before the fragment comes close to finishing all of its code. Any idea? – OxenFreeHorchata Mar 22 '16 at 20:41
  • Well, onResume is the last thing that a fragment run before complete. Just one question: Are you running Google Maps on that fragment? Because if you want to run something before google maps is complete, you need to put it on onMapReady() method – Jordan Junior Apr 01 '16 at 04:45
1

You're confused. You don't run a fragment. You display it. There is no way of "waiting for a fragment to complete" because fragments don't have the concept of completion. If you have a fragment that does something then wants to notify the activity to do something (which may include getting rid of that fragment) the way to do it is to pass the fragment an callback to the Activity that it will call when needed (such as when the user presses a save button).

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thank you, that makes more sense. I was trying to get rid of the fragment after it completed all of its code, but to no avail. Do you have any advice on going that path? – OxenFreeHorchata Mar 22 '16 at 19:53