save variables after quitting application?

前端 未结 3 1958
说谎
说谎 2020-12-08 15:34

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

相关标签:
3条回答
  • 2020-12-08 15:56

    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!

    0 讨论(0)
  • 2020-12-08 15:59

    Use SharedPreference, this is a better option.

    To see this tutorial.

    0 讨论(0)
  • 2020-12-08 16:13

    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");
    
    0 讨论(0)
提交回复
热议问题