Search code examples
androidandroid-fragmentsannotationsonsaveinstancestateonrestoreinstancestate

How to save fragment state with annotations?


I have a little project, one activity and two fragment. I have started from the "Bottom Navigation Activity" sample on a new projet.

The I use the Android Annotations (https://github.com/androidannotations/androidannotations/wiki) for injecting my fragment, It display correctly but when I rotate, I loose all my information and the app display the first fragment, even if I displayed the second one. I tried to save my data, from an edit text with a Bundle object, in the "onSaveInstanceState" method, I get back it in the "onActivityCreated" or in the "onCreate" method but after their method were re-call and my data desappear.

I don't know how to save which fragment was displayed and how re-displayed it with the android annotations.

In my Activity class I have those methods :

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

And in my main fragments :

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        if(dpdEditText != null){
            rttNumberTemp = rttEditText.getText().toString();
            outState.putString("rttNumberTemp", rttNumberTemp);
        }
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(Tag, "onActivityCreated");
        if(savedInstanceState != null){
            Log.d(Tag, "onActivityCreated if");
            updateEditText(rttEditText,savedInstanceState.getString("rttNumberTemp"));
        }

    }

So my question is how can I save my fragment, and its data and which fragment is displayed ?


Solution

  • I finally find my mistake. In my main activity I have the following method :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
    }
    

    So the program call the view by the injection and call it again with the setContentView. So I update the method like that :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    }