Christopher Treanor
Christopher Treanor

Reputation: 515

Is it possible to save a variable value in Android (in memory), even after closing the application? If so, how?

How is it possible to save a variable value in an Android app? Can the value be saved in memory? I am planning to save a float value in my application, so the next time the app is opened, the previous value will be loaded. How do I go about this? Shared Preferences or something else?

Upvotes: 6

Views: 7585

Answers (3)

Chintan Soni
Chintan Soni

Reputation: 25267

Yes. SharedPreferences is the best available option.

To store float value:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("storedFloat", storedFloatPreference); // value to store
editor.commit();

Also check this: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putFloat(java.lang.String,%20float)

Check this SO question. It nicely answers your question: How do I get the SharedPreferences from a PreferenceActivity in Android?

Upvotes: 5

Raghunandan
Raghunandan

Reputation: 133560

Yes its possible use shared preferences.

http://developer.android.com/reference/android/content/SharedPreferences.html

http://developer.android.com/guide/topics/data/data-storage.html#pref

You can also use sqlite data base to store the data and retrieve when you need it.

Your other storage options. you could store your values to a file in memory.

http://developer.android.com/guide/topics/data/data-storage.html

Upvotes: 1

codeMagic
codeMagic

Reputation: 44571

Look at the Storage Options Docs to be sure you pick the most appropriate type for you but if its just one value then SharedPreferences should work fine for you.

See The Docs for a good example on how to use SharedPreferences

Upvotes: 0

Related Questions