6

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?

Christopher Treanor
  • 505
  • 2
  • 8
  • 13

3 Answers3

5

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?

Community
  • 1
  • 1
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
  • If I use SharedPreferences, how do I save float values using it? – Christopher Treanor Aug 22 '13 at 15:55
  • @ChristopherTreanor http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values. if you search on stackoverflow you will find more posts related – Raghunandan Aug 22 '13 at 15:57
1

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

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

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

codeMagic
  • 44,549
  • 13
  • 77
  • 93