【问题标题】:Boolean and sharedpreference布尔值和共享首选项
【发布时间】:2013-09-24 18:03:21
【问题描述】:

嘿,我正在尝试制作自己的应用程序,我已经在网上搜索了信息,但我不明白其他人认为有帮助的解决方案。但我有一个小问题。我希望应用程序在关闭应用程序时保存布尔值 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();
}

【问题讨论】:

    标签: android eclipse boolean


    【解决方案1】:

    您在尝试保存时输入的是 true 而不是变量。

    【讨论】:

    • 我现在尝试对其进行编辑,当我加载应用程序时,它一直将其加载为 false。我尝试将加载首选项也更改为变量,但这没有帮助。
    【解决方案2】:

    像这样在提交后调用 super.onPause:-

    @Override
    protected void onPause() {
        SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1);
         Editor edit = sp.edit();
         edit.putBoolean("stop", stopValue);
         edit.commit();
         super.onPause();
    
    
    }
    

    【讨论】:

    • 它有效.. 谢谢.. 是因为在保存值之前调用了 pause 方法吗?
    • 是的,当你调用 super.onPause() 时框架会暂停活动
    猜你喜欢
    • 2017-10-28
    • 1970-01-01
    • 2019-01-09
    • 2012-08-04
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    相关资源
    最近更新 更多