android 如果重新打开应用程序,则不保存共享首选项

4bbkushb  于 2022-12-21  发布在  Android
关注(0)|答案(5)|浏览(119)

我的sharedpreferences不保存,如果我重新打开我的游戏,我以前保存的数据与SharedPreferences不加载,设置我的当前活动再次恢复正常或默认
这是menu.class中我的按钮的图像

这是我的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

和SharedPreferences代码工作正常,my menu.class中的每个按钮都与代码一起工作并可见!
但如果我退出应用程序,它又恢复正常了

有人能解决我的问题吗?

63lcw9qa

63lcw9qa1#

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

onCreate方法在Activity生命周期需要时运行,尤其是在打开应用时。因此,每次创建Activity时,您都将首选项级别设置为1。这就是问题的原因。

busg9geu

busg9geu2#

问题是,在您的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", 6);
    editor.putInt("Hints", 6);          
    editor.putInt("Level", 1);  
    editor.commit();
}

你不需要检查确切的字段,它只是一个例子。根据你的需要和游戏逻辑调整它。
请看一下Activity的生命周期,以了解为什么会发生这种情况。

(图表source
每次打开应用程序时,都会调用onCreate()方法,因此您的首选项会在读取之前重置。
更多关于here生命周期的信息。

    • 编辑:**以下代码段显示了解决问题的一种方法。
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();
}
    • EDIT2:**您也可以将此逻辑放在onResume()方法上,只要您将其从onCreate()中删除即可,否则您将检查这些条件两次;)
vsdwdz23

vsdwdz233#

我认为你没有检查Menu.class中的共享首选项的存在值。你只是简单地分配了一个默认值,而没有正确地检查共享首选项是否包含数据。在onCreate中
在Menu.class的OnCreate上尝试此操作

SharedPreferences.Editor editor = pref.edit();   
//check it with your default value.I used default value as 0   
int lifes=pref.getInt("Lifes", 0);
if(lifes==0)
editor.putInt("Lifes", 6);
//check it with your default value.I used default value as 0 
 int hints=pref.getInt("Hints", 0);
 if(hints==0
 editor.putInt("Hints", 6);          
 //check it with your default value.I used default value as 0
  int level=pref.getInt("Level", 0);
  if(level==0)
  editor.putInt("Level", 1);  
  editor.commit();
wz1wpwve

wz1wpwve4#

这是因为当您启动应用时,menu.class会通过menu.class文件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() // Check your shared preferences already not available then initialise it
{
     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();
}
sd2nnvve

sd2nnvve5#

每次创建“活动”时,都要重置保存的Preferences

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

只有当它们发生更改时,才应保存Preferences

相关问题