Save the instance of a fragment

0

MainActivity calls fragment when started.

I have tabs that alternate with fragments. I trace a route in one of the fragments and when leaving, clicking on the tab and returning, the route disappears, I would like it to be instantiated yet.

I would like, for a bundle perhaps, that when returning from another tab, I can continue with the route drawn on the screen.

If someone can help me in this matter. Save the Fragment State?

I tried to implement something like the answer above but it did not work.

    
asked by anonymous 25.08.2016 / 02:20

1 answer

1

Look, you can use the fragment life cycle as onActivityCreated . Generally this kind of situation of losing data and having to recover happens, for example, when the screen is rotated. In this case, to write a route, you basically need a array of coordinates right ?! So come on, see the code below and adapt it to your needs:

public class ExampleFragment extends Fragment {
    private List<String> myData;

    @Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("list", (Serializable) myData);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            myData = (List<String>) savedInstanceState.getSerializable("list");
        } else {
            if (myData != null) {

            } else {

                myData = computeData();
            }
        }
    }
}

Of one observed in these gifs referring to the moment in which it saves and the moment of restoration of a Fragment :

Saving and Restoring State

Ifoundthis article and found it very interesting. It's worth reading.

    
25.08.2016 / 06:53