Skip to content Skip to sidebar Skip to footer

Keep Variables After Leaving Activity

I am trying to find a way to keep my variables constant throughout the life of the app. The way I have designed the app is that a user clicks on a class and submits a grade. What

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"