0

In my Android application I have used a Constants class to store app data like login user information using static variables. I'm able to use that data throughout the app. But, when I leave my app in background for a long time and start it later, it crashes. The error stack contains a NullPointerException on the variable that I have referenced from Constants class.

traj
  • 81
  • 2
  • 8
  • If you have your application on background for long time and using the rest of the applications the Android OS will automatically free's the lately used apps memory try to save those credentials in some persistent storage like shared preferences or file. – N20084753 Oct 29 '13 at 04:10
  • Here is a great link explaining the problem: [Android static object lifecycle](http://stackoverflow.com/questions/1944369/android-static-object-lifecycle-application-act-crazy). The solution is to use a persistence mechanism (like SQLite or Shared Preferences) as needed. Look here for more details: [Android Storage Options](http://developer.android.com/guide/topics/data/data-storage.html) – paulsm4 Oct 29 '13 at 04:11
  • how could I prevent "Unfortunately Stopped" error in that case? and redeirect the user to login screen or Dashboard in my app? – traj Oct 29 '13 at 04:42

2 Answers2

1

When your application is cleared from memory, all static variables (which are obviously stored in memory) are cleared as well. The Saving Data Training details many of the available solutions to store data so that it can be properly restored even if the application is killed. Simple key-value pairs can be stored in Shared Preferences.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
0

From static or any variables you couldn't retrieve the last changes after the application is shutdown. For that you need to save the values into file system or any lightweight databases(for example SQLite). Whenever you start you application you need to load into your static fields from the file or database.

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64