Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 option I guess. Other one I thought was to use android.app.Application class but I am not able to get what I want from that. Can we actually do it using android.app.Application? Or then any other method for 3 to 4 variables.

like image 551
impossible Avatar asked Oct 28 '25 05:10

impossible


2 Answers

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);
like image 176
rahimli Avatar answered Oct 31 '25 03:10

rahimli


Use SharedPreferences. SharedPreference provides an easy mechanism to persist a value across the life of an app.

like image 35
Tony Avatar answered Oct 31 '25 02:10

Tony