Curio
Curio

Reputation: 1371

Android:How to save perennialy a variable?

I have a variable and I want to change it only the first time that I start my app. For example:

  1. I open the app: Variable is not initialized. Variable changes to 4.
  2. I close the app
  3. I open the app Variable is 4.

And so on.

How can I do this?

Upvotes: 0

Views: 57

Answers (2)

Gilad Eshkoli
Gilad Eshkoli

Reputation: 1253

You can also write to a local file and use SQLite for that purposes if you would like to persist big object's data.

Upvotes: 0

Sai Raman Kilambi
Sai Raman Kilambi

Reputation: 888

I guess you are new to Android. You can save the values using "SharedPreferences".

Check this link : https://developer.android.com/training/basics/data-storage/shared-preferences.html

Also check out this example :

https://www.tutorialspoint.com/android/android_shared_preferences.htm

You can use this code :

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

Here, MyPREFERENCES is the file name. Replace the "value" with the variable name. Again, if you want to retrieve the value, then use:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key", true);
//There are other methods like getInt(),getDouoble().getString() depending on the type of value

Upvotes: 1

Related Questions