I have the following situation. My activity A contains fragment B. Inside of B, a spinner determines whether fragment C1 or fragment C2 is displayed below the spinner. Each of these contains EditText
fields where the user enters data. How to persist the data in the fields on rotation and remove it on fragment replacement or after the activity finishes?
My current approach is the following. I retain fragment B and inside of C1 and C2 I have static variables storing the data of the fields. So, in onViewCreated
in C1 and C2 I restore the state of the fields (e.g. after rotation). When the user clicks on buttons in the activity (Save
or Cancel
), I set all variables of the current fragment (C1 or C2) to null
. So far, so good.
Now the problem is when I open A, so that I see C1, then switch to C2, then go back to the previous activity. I open activity A again and C1 opens by default. But I have cleaned only C2, as this was the fragment displayed before closing the activity. So, my problem is that although I have replaced fragment C2, its variables are not set to null
. How/where to do that? So that the variables remain on rotation but not on replacement of the fragment. And what do I do when the user clicks Up
or the hardware back button? It would be great, if the fields could be also cleaned.
I assume, there should be some standard way of doing all this, without 100 additional variables. Could someone give me an advice?