Keep Variables After Leaving Activity
Solution 1:
In 3 way you can achieve your function.
1. Global Variables
You can use global variable by defining any variable with modifier public static
like
publicstaticStringGRADE="10";
You can use it in any class in the app by CLASS_NAME.GRADE
. Like
Stringgrade= CLASS_NAME.GRADE;
Note: it will loose its value when you close the app.
2. SharedPreference
For retaining value after app closes, you need to use SharedPrefeernce
or SQLite database.
Here is the example of how to use SharedPreference.
Initialize SharedPreference as below in your activity
SharedPreferencessp= getSharedPreferences("app_name", Context.MODE_PRIVATE);
Get value from SharedPreference as below
Stringgrade= sp.getString("grade", "0");
Set value to SharedPreference as below
sp.edit().putString("grade", "5").commit();
3. SQLite
You can use SQLite database to store your own structure data. You can create different tables and store/retrive date according to your requirements. Here is some examples: http://www.vogella.com/tutorials/AndroidSQLite/article.html
Solution 2:
You probably want to use SQLite to store your data.
https://developer.android.com/training/basics/data-storage/databases.html
Solution 3:
You can use the SharedPreferences file to store variables as key value pairs when the user is about to exit the activity (onPause) and when the activity is re-created you can read the data from that Shared preferences file.
http://developer.android.com/guide/topics/data/data-storage.html#pref
Post a Comment for "Keep Variables After Leaving Activity"