24

I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game)

How can I do this?

EDIT: Here my code:

TextView test1;
String punkte = "15";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SharedPreferences save = getSharedPreferences(punkte, 0);
    save.edit().putString("score", punkte);

    SharedPreferences load = getSharedPreferences(punkte, 0);
    String points = load.getString("score", "0");

    test1 = (TextView) findViewById(R.id.test1);
    test1.setText(points);

    }    
Stupe
  • 305
  • 1
  • 2
  • 11

3 Answers3

50

You should be using SharedPrefences. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there.

Here is a code sample.

To access variables:

SharedPreferences mPrefs = getSharedPreferences("label", 0);
String mString = mPrefs.getString("tag", "default_value_if_variable_not_found");

To edit the variables and commit (store) them:

SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("tag", value_of_variable).commit();

Make sure both "tag" fields match!

Mxyk
  • 10,678
  • 16
  • 57
  • 76
6

Use SharedPreference, this is a better option.

To see this tutorial.

edwoollard
  • 12,245
  • 6
  • 43
  • 74
MAC
  • 15,799
  • 8
  • 54
  • 95
  • 1
    can you explain how I use it? – Stupe Jul 27 '12 at 13:27
  • so there is nothing in your code you have done that mentioned in link. do some effors dear. i cant do code for you. – MAC Jul 27 '12 at 14:40
  • 6
    @MAC for the purpose of making SO a place with answers instead of just a place with links, it may also be good to do an abstract of the solution you're linking there – Sergi Juanola Jun 21 '17 at 09:49
3

sample code: save:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString("statepara1", ts);
editor.commit();

get:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);    
String ret = settings.getString("statepara1", "0");
enjoy-writing
  • 520
  • 3
  • 4