SharedPreference未按预期工作

问题描述 投票:4回答:2

我有一个活动,我只想在第一次运行应用程序时运行。我检查了一个返回布尔值的指定共享首选项。如果它返回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);
            }
android sharedpreferences
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
}
© www.soinside.com 2019 - 2024. All rights reserved.