Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping object's state when user presses "Back" button

I have an app in which I programmatically create an EditText view. I assign an ID to that view using setId()

myEditText.setId(100);

so that Android automatically saves that object's state when pausing/stopping the app (as I was advised to do here). It works in these cases:

  • (1) When I leave the app using the "Home" button: if I then come back to the app, the object's state (displayed text) is restored, as expected.
  • (2) On a screen orientation change (which involves Android automatically destroying the activity and restoring it through a Bundle). The object state is also kept.

However, it doesn't work in this case:

  • (3) When I leave the app using the "Back" button: if I then come back to the app, the EditText object is empty.

Any explanation as to why this happens? Does Android really distinguish between leaving the app with "Home" and with "Back"? According to the documentation, the object's state should be automatically preserved, through a Bundle, even when the activity is destroyed. And that clearly happens in case (2). But not in case (3)!

If this is normal behaviour, how could I have the app's state automatically saved and restored when the user presses "Back"? I know I could use the SharedPreferences for that, but I'd rather have Android do that automatically, just as it does in cases (1) and (2).

This happens at least in Android 4.0 and 4.2 (I haven't tested others).

like image 665
Luis Mendo Avatar asked Oct 02 '22 01:10

Luis Mendo


1 Answers

You really should study activity life cycles as there are many many ways to solve the problem. Since your activity is typically pulled off of the stack and destroyed when you navigate back one quick but not necessarily the best way is to make sure your activity flagged as singleTop or singleInstance in the manifest that way it is not pulled off of the stack and recreated when you navigate back and forth. You could also use the singleton Application class. Or pass the text back and forth as params. Or use a database. Or use MVC or some other programming paradigm that will allow your views to be destroyed and recreated with out the data populating them going with it. Lots of "or's". Study activity life cycles and then look at how you have your application architecture setup already and choose the method that will work best for you.

http://developer.android.com/training/basics/activity-lifecycle/index.html

http://developer.android.com/guide/components/tasks-and-back-stack.html

like image 134
lentz Avatar answered Oct 13 '22 10:10

lentz