In my app, I have a singleton class which communicates with all the activities and has all the app data. All of a sudden the object has started becoming null. It seems to be happening when i change top level activity (using intent). Is there a simple method the make sure that as long as my activity is visible the object persists.
3 Answers
I think a new top-level activity is made in a new process (reading between the lines in http://developer.android.com/reference/android/app/Activity.html#ProcessLifecycle).
Android is more likely to kill of the process of an Activity that lives in the background, and that includes when a top-level activity drops behind another.
I think a better solution might be to have your Singleton transparently initialise itself if null, loading and saving any state from disk if necessary (a pretty standard singleton paradigm). There's no way to solve your problem with a single instance across the old and new activities.
Edit: I'm not convinced that a Service is the way to go. Services are for carrying on with activities in the background of the phone, whereas what you're talking about is data storage and retrieval. The most natural way to do that, I think, is for each Activity to be robust to whether it's the first activity or not.

- 7,126
- 4
- 41
- 67
If it were me, I'd be using a Service
instead of a singleton to manage app data that is shared across activities. It would be far more robust.
See the Services Developer Guide for more information.

- 11,287
- 1
- 28
- 22
-
I am very new to android. In my scenario i am making a click based game. so on every input the singleton object does some processing and presents the user with new activity. how do i do it with service. Also could you give me link to read on service. – chandings Jul 03 '12 at 21:17
-
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. How is that an answer for data persistence in the app? – tread Feb 27 '15 at 06:35
You must be using the singleton wrong, a singleton object should be valid during the duration of the application lifetime. It doesn't matter if activities within this application are recreated and destroyed.
However, if your singleton is referencing the activities (e.g. activity context, activity variables like widgets) then it's possible at some point those variables/context will be invalid, even if the singleton object itself is still valid.

- 15,087
- 4
- 49
- 46