2

In my application I have number of activities, Application is used to store global variables like currentUser etc.

Sometimes, when I pressing Home button and then returning to my application via Recent, an Application object created again, with null-field instead of currentUser.

How can I avoid that?

skayred
  • 10,603
  • 10
  • 52
  • 94
  • You can find this helpful: http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables/4642069#4642069 – Vit Khudenko Nov 20 '11 at 09:59

2 Answers2

0

When your app goes to the background Android has the option of keeping it around or closing it completely at any time. Often when a separate app is brought to the foreground that is resource intensive, Android will start killing off other apps that are in the background and not actively doing anything.

Really the only way to stop Android from potentially killing of your app is to have a Service running in your app that requests to be in the foreground. Of course, by doing so your app will be required to display an icon in the status bar.

The takeaway: Your best bet is to store a key representing your currentUser in a Preference or datastore rather than depend on a global variable being held on your Application object.

Jonathan Schneider
  • 26,852
  • 13
  • 75
  • 99
0

you should use the onPause() method to write any persistent data to storage, and/or you should implement onSaveInstanceState(Bundle) which is called before the activity goes to background so you'll be able to save any dynamic data in your activity into the given Bundle, to be later received in onCreate(Bundle).

More information on Activity lifecycle here

Eitan
  • 1,012
  • 7
  • 25