0

I explain the scenario below:

Activity1(fragment1) -> Activity1(fragment2) -> Activity1(fragment3) -> Activity2(fragment4)(OK-button)

if i click on OK button on fragment4 in Activity 2, i should land onto Activity1(fragment2) and upon clicking on back button on fragment 2, it should land onto fragment1.

I tried the following code:

activity?.supportFragmentManager?.popBackStack() 

But it doesn't work. Any help or suggestion on how to resolve this issue. You may ask why i'm using lots of fragments here but i really don't have any other options.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Reddy
  • 65
  • 1
  • 10

1 Answers1

0

When you click on OK button in Activity2(fragment4), just put an entry in sharedPreference before calling Activity1 intent like this:

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(key, "1");
editor.commit();

then call your Activity1:

Intent Activity1 = new Intent(getActivity(), Activity1.class);
startActivity(Activity1);

Now in your Activity1, before setting the contentview, just check the shared preference if it have a variable key with value 1 stored in it. If it contains a value 1, then load fragment2 in the frame layout frm. Like this:

sharedPreferences = getActivity().getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if (sharedPreferences.contains(city)) {
       FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
       fragmentTransaction.replace(R.id.frm,new fragment2()).addToBackStack(null).commit();
}

When this activity is called normally, shared preference will not have the value 1 in key, so fragment1 will be loaded as your normal flow.

Now, when you move to next fragment from here, just store 0 in key variable in shared preference. This can be done in onDetach() method of the fragment2

Also to go back to fragment1, you can follow this answer for more detailed solution.