代码之家  ›  专栏  ›  技术社区  ›  RichFounders

如果应用程序重新打开SharedPreferences而不保存布尔值

  •  0
  • RichFounders  · 技术社区  · 9 年前

    我的项目中有以下代码 menu.class

    f1 =(Button)findViewById(R.id.f1);      
    f1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            // TODO Auto-generated method stub
            Intent intent = new Intent ();
            intent.setClassName ("com.example.aplication", "com.example.application.levelone");
            startActivityForResult (intent, 0);              
        }             
    }); 
    }
    
    public void onActivityResult (int requestCode, int resultCode, Intent intent) {
        super.onActivityResult (requestCode, resultCode, intent);
    
        f2=(Button)findViewById(R.id.f2);      
        f2lock=(ImageView)findViewById(R.id.f2lock);
    
        switch (resultCode) {
            case 11: f2.setVisibility(View.VISIBLE);
                     f2lock.setVisibility(View.GONE);               
        }                                  
        SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
        boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
    
        if(levelTwoUnlocked){
            f2.setVisibility(View.VISIBLE);
            f2lock.setVisibility(View.GONE);
        }
        else {
            f2.setVisibility(View.GONE);
            f2lock.setVisibility(View.VISIBLE);
        } 
    
        f2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                Intent intent = new Intent ();
                intent.setClassName ("com.example.application", "com.example.application.leveltwo");
                startActivityForResult (intent, 0);              
            }             
        });     
    }
    

    代码运行良好。 f2 按钮设置为可见 f2lock 看不见的 但当我重新打开应用程序时 f2(f2) 按钮返回可见。 我的首选项代码没有完成吗?

    已更新

    我已经这样更改了偏好代码

        SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
        SharedPreferences.Editor ed = preferences.edit();
        boolean levelTwoUnlocked = preferences.getBoolean("f2", true);
        ed.commit();                
    

    当我重新打开应用程序时,它仍然存在相同的问题

    1 回复  |  直到 9 年前
        1
  •  0
  •   adelphus    9 年前

    您正在检索的值 f2 ,但看起来你没有把它保存在任何地方。

    preferences.getBoolean("f2", true);
    

    这将返回上次保存的值 f2(f2) true 如果 f2(f2) 不存在(即您从未将其保存在SharedPreference实例中)-它不会为您创建或保存SharedPreferences实例中的任何值。

    要保存值,需要创建SharedPreferences编辑器,设置要保存的值并提交:

    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("f2", levelTwoUnlocked);
    editor.commit();
    

    下次你读 f2(f2) 价值,它将具有您上次承诺的任何价值。