如果我在我的应用程序中添加一个号码,请说高达15,我想确保下次打开我的应用程序,无论它是否崩溃,手机重启,或应用程序已退出;它应该从15号而不是0号继续。我该如何处理呢?
我试过这样的事情。这可能是错误的,不知道如何解决它。
public class MainActivity extends Activity {
private int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.but);
final TextView txt = (TextView) findViewById(R.id.txt);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
i++;
txt.setText(" " + i);
i++;
editor.putInt("Scores: ", i);
editor.commit();
}
});
}
}
答案 0 :(得分:2)
public class MainActivity extends Activity {
private int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// let i be previously saved value or default to zero
i = app_preferences.getInt("Scores: ",0);
Button btn = (Button) findViewById(R.id.but);
final TextView txt = (TextView) findViewById(R.id.txt);
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = app_preferences.edit();
i++;
txt.setText(" " + i);
//i++; maybe DONT really increment twice (unless thats what you intended)
editor.putInt("Scores: ", i);
editor.commit();
}
});
}
}