加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如果重新打开应用程序,则不保存SharedPreferences

发布时间:2020-12-15 04:29:03 所属栏目:Java 来源:网络整理
导读:我的共享偏好不会保存,如果我重新打开我的游戏,之前保存的SharedPreferences数据未加载,我当前活动的设置再次恢复正常或默认 这是menu.class中我的按钮的图像 这是我的menu.class的以下代码 @Override protected void onCreate(Bundle savedInstanceState) {
我的共享偏好不会保存,如果我重新打开我的游戏,之前保存的SharedPreferences数据未加载,我当前活动的设置再次恢复正常或默认

这是menu.class中我的按钮的图像

enter image description here

这是我的menu.class的以下代码

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.menu);
    SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); 
    SharedPreferences.Editor editor = pref.edit();      
    editor.putInt("Lifes",6);
    editor.putInt("Hints",6);          
    editor.putInt("Level",1);  
    editor.commit();

     f1=(Button)findViewById(R.id.f1);

     f2=(Button)findViewById(R.id.f2);
     f2lock=(ImageView)findViewById(R.id.f2lock);


   f1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                // TODO Auto-generated method stub
                Intent i =new Intent(menu.this,levelone.class);
                startActivity(i);             
            }             
        }); 

    f2.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v){
           // TODO Auto-generated method stub
              Intent i =new Intent(menu.this,leveltwo.class);
              startActivity(i);          
            }             
      });

    f3=(Button)findViewById(R.id.f3);
    f3lock=(ImageView)findViewById(R.id.f3lock);

}
public void onResume() {
super.onResume();

   SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); 
   levelunlocked = pref.getInt("Level",0); 

   if(levelunlocked == 2)

    {
        f2.setVisibility(View.VISIBLE);
        f2lock.setVisibility(View.GONE);
    }
    if(levelunlocked == 3)

    {
        f3.setVisibility(View.VISIBLE);
        f3lock.setVisibility(View.GONE);
    }   

       SharedPreferences.Editor editor = pref.edit();
       editor.putInt("Level",levelunlocked);
       editor.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.splashscreen,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button,so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

我在levelone.class中有这个代码来从menu.class获取默认值

int gamelifes,gamehints,gamelevel,index=0; 


SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE);
gamelifes = pref.getInt("Lifes",0);
gamehints = pref.getInt("Hints",0);
gamelevel = pref.getInt("Level",0);

//the value from sharedpreferences is use to be a text by use code below

lifes1 =(TextView)findViewById(R.id.lifestext1);
lifes1.setTextColor(Color.RED);
lifes1.setText(String.valueOf(gamelifes));   

hints1 =(TextView)findViewById(R.id.hintstext1);
hints1.setTextColor(Color.GRAY);
hints1.setText(String.valueOf(gamehints));

并使用新数据保存共享偏好

String answer=edittextanswer1.getText().toString();              
            if(answer.equalsIgnoreCase(answer1[index]))
            {
                gamelevel++;                
                image.setVisibility(View.GONE); 
                finishbutton.setVisibility(View.VISIBLE);  
                SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); 
                SharedPreferences.Editor editor = pref.edit();      
                editor.putInt("Lifes",gamelifes);
                editor.putInt("Hints",gamehints);          
                editor.putInt("Level",gamelevel);  
                editor.commit();
            else
            {    
            tryagain1.setVisibility(View.VISIBLE);
            gamelifes--;
            lifes1.setText(String.valueOf(gamelifes));
            }

然后,如果单击完成按钮,它将是这样的

finishbutton.setOnClickListener(new View.OnClickListener() {

      public void onClick(View v){
          finish();
      }
   });

所以levelone.class完成并返回menu.class

enter image description here

和SharedPreferences代码工作正常,我的menu.class中的每个按钮都与代码一起工作并且可见!

但如果我退出应用程序,它会再次恢复正常

enter image description here

有人有解决方案来解决我的问题吗?

解决方法

事实上,在你的onCreate()方法中,你总是在这里重置共享首选项:

SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); 
SharedPreferences.Editor editor = pref.edit();      
editor.putInt("Lifes",6);
editor.putInt("Hints",6);          
editor.putInt("Level",1);  
editor.commit();

只需使用if语句检查该文件是否已存在于该行之前.这应该够了吧.

就像是:

if (pref.contains("Level")) {
    // Do not reset
}
else {
    // Create the prefs
    SharedPreferences.Editor editor = pref.edit();      
    editor.putInt("Lifes",1);  
    editor.commit();
}

您不必检查确切的字段,这只是一个示例.根据您的需求和游戏逻辑进行调整.

查看Activity生命周期,了解发生这种情况的原因.

enter image description here

每次打开应用程序时,都会调用onCreate()方法,因此在读取之前会先重置prefs.

更多关于生命周期here.

编辑:以下snnipet显示了解决问题的一种方法.

public static final String PREF_LIFES = "Lifes";
public static final String PREF_HINTS = "Hints";
public static final String PREF_LEVEL = "Level";
public static final String PREF_IS_SET = "isSet";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.menu);

    SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); 

    // Check wether the pref is set or not.
    if (pref.getBoolean(PREF_IS_SET.false)) {
        // The prefs is set. Do some game logic here. Like checking for lifes.
        if (pref.getInt(PREF_LIFES,0) == 0) {
            // Player is "dead",reset it.
            resetPrefs(pref); 
        }
        else {
            // Player is alive,do whatever you want,or do nothing at all.
        }
    }
    else {
        // if it's not set,just create it.
        resetPrefs(pref);
    }

    // ...   
}

private void resetPrefs(SharedPreferences pref) {
    SharedPreferences.Editor editor = pref.edit();      
    editor.putInt(PREF_LIFES,6);
    editor.putInt(PREF_HINTS,6);          
    editor.putInt(PREF_LEVEL,1);
    editor.putBoolean(PREF_IS_SET,true);
    editor.commit();
}

编辑2:您也可以将此逻辑放在onResume()方法上,只要您从onCreate()中删除它,否则您将检查这些条件两次;)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读