Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

android - save variables after quitting application?

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);

    }    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...