0

如果我在我的应用程序中添加一个数字,比如说最多 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();
        }
    });


}

  }
4

1 回答 1

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


}

  }
于 2013-07-30T15:15:55.937 回答