Reputation: 347
In an app I'm making I have an Object to a class called Preferences in my MainMenu activity. I want to use this object in several pages. In the object is a class which contains an array with numbers. When I use it in another activity (Film) it changes one of the numbers in the object. Then I go back to the main menu and into a new activity (CurrentPrefs) in which I display the array of numbers on the screen. When I displayed the numbers they didn't contain the changes made in the Film file. So I started testing around with the variables a bit.
When I start the MainMenu, which is the start activity, it sets the object. Then when I enter film and check the object it still has the same name (object.toString()). I also checked to make sure that the values where changed correctly which they were.
Next I went back to MainMenu and checked again. The object still had the same name and the value were also like I changed them in Film.
Finally I entered the CurrentPrefs activity and there it goes wrong. The object suddenly has a different name and it also no longer contains the changes I made to it.
Why has the object changed and, more importantly, how can I make sure it doesn't change and stays the same everywhere?
Upvotes: 1
Views: 62
Reputation: 354
If you well know activity's lifecycle you can also understand why it happens. Probably some of your operation are delegated to onResume()
method which is called whenever activity comes back from onPause()
or immediately after onCreate()
, while other operations reside in onCreate()
called only when activity starts or after onDestroy()
. I advise you to control this and trying to move all setText()
in onResume()
so that every updated object's variable will be read again.
Upvotes: 1
Reputation: 1850
There are any number of reasons why your object's values changed. Perhaps the previous Activity
got destroyed and recreated without you realizing it.
You should check out Android's SharedPreference
class. It is a way to store, edit, and retrieve preferences and have access to them in any Activity
:
http://developer.android.com/reference/android/content/SharedPreferences.html
Upvotes: 1