-4

How can I save and load variables constantly ? I find the Shared-Preferences but dont understand it well. For example I got a variable which is called

int global_coins

How can I load or save it ? Thank You !

user3202845
  • 41
  • 1
  • 7
  • 2
    What don't you understand using SharedPreferences? This is well explained here (and the others options available to save app datas): http://developer.android.com/guide/topics/data/data-storage.html – Alexis C. Feb 16 '14 at 22:21
  • If you don't understand any particular thing about SharedPreferences, then it's better to ask about it. You question is too vague and there's no way to answer it. – Egor Feb 16 '14 at 22:23
  • Maybe someone can give a example ? – user3202845 Feb 16 '14 at 22:24
  • http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values – gipinani Feb 16 '14 at 22:27
  • @user3202845 There is an example in the link I posted. And i'm sure you can find plenty using your favorite search engine. – Alexis C. Feb 16 '14 at 22:27

1 Answers1

2

You would do something like this to store a variable:

SharedPreferences sp = context.getSharedPreferences(context.getString(R.string.shared_preferences_file), 0);
Editor editor = sp.edit();
editor.putInt(context.getString(parameterRid), value);
editor.commit();

And something like this to read a variable:

SharedPreferences sp = context.getSharedPreferences(context.getString(R.string.shared_preferences_file), 0);
return sp.getInt(context.getString(parameterRid), defaultValue);

You should really read the documentation for SharedPreferences, it's really simple to understand and the official guide to data storage is very useful.

Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114