0

I have three fragments (A,B,C) in an activity. Fragment A leads to B and Fragment B leads to C. In Fragment C, the user has two options. He could either go back to Fragment A or he could destroy the entire activity. If he chooses to go back to Fragment A, I want the current set of data to be saved in a list in fragment C, then same cycle is repeated. However when he reaches fragment C the next time I want the current data to the added to that list.

How can I implement this using onPause() and onResume()? If there is a better way of doing this, kindly let me know. I cannot store in shared preferences since the data will be an ArrayList of an object.

I would appreciate if anyone can show me a basic structure of how we could implement this in a code.

vinitpradhan18
  • 51
  • 1
  • 10
  • You can save you data on a Shared Preference. – Sushin Pv Oct 10 '17 at 09:50
  • https://stackoverflow.com/questions/23024831/android-shared-preferences-example – Sushin Pv Oct 10 '17 at 09:51
  • I'd not recommend to use the Shared Preferences as their purpose is to keep the data when the app is killed, not to pass data between activities/fragments. There are other methods for that. – Eselfar Oct 10 '17 at 10:09

1 Answers1

0

Option 1

You need to implement a communication between the Fragment and the Activity. The Activity keeps the object with all the information and the Fragment get the object when resumed and update it if necessary.

Here is an example of the official documentation

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    ...
}

Then on onResume() the Fragment call mCallback.getObject() to get the information. And then update the object.

Option 2

The other option is to create an external manager class which will keep the data an will be accessed by all the Fragments. It could be a singleton but it needs to be destroyed when the Activity is destroyed

Eselfar
  • 3,759
  • 3
  • 23
  • 43