1

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?

Antiohia
  • 1,142
  • 13
  • 37

1 Answers1

0

I think the problem is since you retain the instance of fragments, activity is also being retained. and looks like you are resuming activity again.

You can try to set false of retain instance when save or cancel pressed.

Good luck.

Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30
  • It doesn't work... The idea is great, I hadn't tried it, but the result is the same as before. When I don't retain the instance and don't clear the fields, the fields remain as they were. When I don't retain the instance and I clear the fields of the current fragment, these are cleared but the ones of the other fragment remain as they were. – Antiohia Jul 10 '14 at 13:58
  • I didn`t write retainfragmentinstance to true, by default it is false and i have nested fragments why edittext in child fragment not clear ? – Asad Mukhtar Jun 20 '19 at 07:21