ArewegoodQ ArewegoodQ - 5 months ago 8
Android Question

Ways to store variables throughout the life time of android app in phone

I am new to Android. I am building a test application where I need to store a variable's value say,

strength
of the user. I want to increase or decrease this
strength
's value whenever user uses the app. And after user closes the app and reopens it on next day, he should find the same value of
strength
.

One way I can think of is to store a local db in phone and read/write each time into that, since there are hardly 3 to 4 such variables. So db is not a good options I guess.
Other one I thought was to use
android.app.Application
class but I am not able to do that. Can we do it using
android.app.Application
or any other method for 3 to 4 variables.

Answer

You can use SharedPreferences to store your variable inside shared preferences. For example, set it like:

SharedPreferences sharedPreferences = context.getSharedPreferences("DATA",Context.MODE_PRIVATE);
sharedPreferences.edit().putString("STRENGTH",yourVar).apply();

Then get it out using:

SharedPreferences sharedPreferences = context.getSharedPreferences("DATA",Context.MODE_PRIVATE);
strength = sharedPreferences.getString("STRENGTH",null);