In android,Google recommends us to save the global variables in Application. But there is a problem, if the android os kill the application because of low of memory, the app
If a variable must persist between executions, you have to do some disk persistence. The easiest way, as suggested by Raghunandan, is using Shared Preferences.
To do this, first request a shared preferences:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key_name", "key_value");
editor.commit(); //important, otherwise it wouldn't save.
You can do this, for instance, in the onStop or onPause of the activity (onPause is always called, but there's no guarantee onStop will be called prior to Honeycomb).
In your onCreate (or when you need the value), you read from SharedPreferences and check if there's a value set, otherwise use a default value:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
String myVariable = prefs.getString("key_name", "default_value");
Now you can use myVariable
with the persisted value or the initial (default) value if nothing was saved before.
For more, see https://developer.android.com/guide/topics/data/data-storage.html#pref
To clarify, PREFS_NAME
is the name of your shared preferences file. Usually, prepend the package name for your application, it's good practice.
As per new guidelines always Consider using apply()
instead of commit
on shared preferences. Whereas commit blocks and writes its data to persistent storage immediately, apply will handle it in the background and will not hamper your other ongoing work.