嘿,我正在尝试创建自己的应用程序,我已经在网上搜索信息,我不明白其他人发现有用的解决方案。但我有一点问题。我希望应用程序保存布尔值stopValue,当我关闭应用程序时,但是当我尝试这个时,它不会保存我关闭应用程序时的值,而是将值设置为true。
我该如何解决这个问题?
感谢您的帮助。
public class Main extends Activity{
Button bStart, bStop;
TextView tvDate, tvKm;
Spinner spinner1;
boolean stopValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bStart = (Button) findViewById(R.id.bStart);
tvDate = (TextView) findViewById(R.id.tvDate);
tvKm = (TextView) findViewById(R.id.tvKm);
spinner1 = (Spinner) findViewById(R.id.spinner1);
boolean stopValue = false;
SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1);
stopValue = sp.getBoolean("stop", false);
stopValue = getIntent().getBooleanExtra("stop", stopValue);
if(stopValue){
bStart.setText("Start");
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent start = new Intent("com.uniqueapps.runner.START");
startActivity(start);
}
});
}
if(stopValue == false){
bStart.setText("Stop");
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent stop = new Intent("com.uniqueapps.runner.STOP");
startActivity(stop);
}
});
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1);
Editor edit = sp.edit();
edit.putBoolean("stop", true);
edit.commit();
}
答案 0 :(得分:1)
在尝试保存而不是变量时,你是真的。
答案 1 :(得分:0)
在提交后调用super.onPause: -
@Override
protected void onPause() {
SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1);
Editor edit = sp.edit();
edit.putBoolean("stop", stopValue);
edit.commit();
super.onPause();
}