0

I have a viewpager with 4 fragments. The first time contains an expandable list view which allows the user to chose something. However when I swipe to the third fragment the view of the first one gets destroyed, so if I swipe back to the first one I don't see the user's selection anymore. Is there a way I can save the state of the first fragment such that when I swipe back from the third or the forth fragment I still will be able to see what the user selected?

Note: I did try to use the setOffscreenPageLimit() method, however it gave me another problem. The last fragment is supposed to send a report with user data, and reset the whole viewpager to the initial state, in case of setOffscreenPageLimit() after sending the report, I still had all the fragments with the user selection.

Thanks in advance.

Keselme
  • 3,779
  • 7
  • 36
  • 68
  • You can communicate to fragments via parent activity. So whenever the report is generated, call a method of activity from the last fragment, which further notifies other fragments to reset. – Vivek Sinha May 21 '18 at 10:49
  • Refer to this link may be it can help you https://stackoverflow.com/questions/6787071/android-fragment-how-to-save-states-of-views-in-a-fragment-when-another-fragmen – Aman Saxena May 21 '18 at 10:49
  • @VivekSinha I actually do have a callback in my MainActivity that responds to the report being sent. However I'm not sure how can I reset all the fragments. – Keselme May 21 '18 at 11:39
  • @AmanSaxena, thanks I'll look into it. – Keselme May 21 '18 at 11:39
  • @Keselme you can directly call fragment's methods from its parent activity using fragment's instance. Use findFragmentById or Tag to get fragment instance, if not already have. See link for more details: https://developer.android.com/training/basics/fragments/communicating – Vivek Sinha May 21 '18 at 11:44

1 Answers1

1

Please Follow steps may this will help you out to sort out your problem. Save all the user selection in onSaveInstanceState and restore when created again in onActivityCreated.

public class MainFragment extends Fragment {

// These variable are destroyed along with Activity
private int someVarA;
private String someVarB;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("someVarA", someVarA);
    outState.putString("someVarB", someVarB);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    someVarA = savedInstanceState.getInt("someVarA");
    someVarB = savedInstanceState.getString("someVarB");
}
}
Mahesh Keshvala
  • 1,349
  • 12
  • 19