SharedPreference无法按预期工作

4

我有一个活动,只想在应用程序第一次运行时运行它。我检查了一个指定的共享首选项,它返回一个布尔值。如果返回true,则启动该活动并将其设置为false,这样下次打开应用程序时就不会运行它。但是我的实现出了问题。每次打开BeforMain1活动都会被打开。有人能建议我代码中的问题在哪里吗?

sharedPreferences = getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor=sharedPreferences.edit();
            boolean  firstTime=sharedPreferences.getBoolean("first", true);
            if(firstTime) {
                editor.putBoolean("first",false);
                Intent intent = new Intent(SplashScreen.this, BeforeMain1.class);
                startActivity(intent);
            }
            else
            {
                Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(intent);
            }
2个回答

5

你忘记提交SharedPreferences的更改。

if(firstTime) {
      editor.putBoolean("first",false);
      //For commit the changes, Use either editor.commit(); or  editor.apply();.
      editor.commit();  or  editor.apply();
      Intent intent = new Intent(SplashScreen.this, BeforeMain1.class);
      startActivity(intent);
}else {
      Intent intent = new Intent(SplashScreen.this, MainActivity.class);
      startActivity(intent);
}

0

我认为这会对你有所帮助,抱歉我的英文不好。

SharedPreferences validation;
SharedPreferences.Editor editorValidation;


validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);

if(validation.contains("firsttime"))
{
        Intent intent = new Intent(getApplicationContext(), MainActivity.class); //create intent with second screen
                startActivity(intent); //call second screen

        /* 
        //this code you will put in your application but is redundant... with the else and comprobation if the firsttime is true or false
         if(Validation.getBoolean("firsttime", false))
        {
            Intent intent = new Intent(SplashScreen.this, MainActivity.class); //create intent with second screen
            startActivity(intent); //call second screen
        }else{
            //if the sharedpreference firsttime is true then call the first screen but it is redundant
            Intent intent = new Intent(getApplicationContext(), BeforeMain1.class); //create var intent with the screem for first time
            startActivity(intent); //call new screen
        }
        */
}else{
    //put the sharedpreference boolean firsttime equal to false
    editorValidation= validation.edit();  // edit the sharedpreference
    editorValidation.putBoolean("firsttime",false); // put false to firsttime
    editorValidation.apply(); //apply(); runs in background, no return anything and commit(); return true or false

    //call screen before the main - for the first time
    Intent intent = new Intent(getApplicationContext(), BeforeMain1.class); //create var intent with the screem for first time
        startActivity(intent); //call new screen
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接