简体   繁体   English

Android:SharedPreferences布尔值

[英]Android: SharedPreferences Boolean

does someone know where the mistake is? 有人知道错误在哪里吗? There is an error in Android Studio. Android Studio中存在错误。

The following is the code for now. 以下是现在的代码。

final String keyFirstTime = "keyFirstTime";

prefsEditor.putBoolean(keyFirstTime, false);

if (keyFirstTime = false) {

Thanks in advance. 提前致谢。

  1. keyFirstTime is a string (see comment) keyFirstTime是一个字符串(请参阅注释)
  2. you are PUTTING a value not getting a value 您正在投入价值而没有价值
  3. You are using an assignment in an if statement 您在if语句中使用赋值
  4. You are comparing a STRING to a BOOLEAN 您正在将STRING与BOOLEAN进行比较

In Activity 1 you should have: 在活动1中,您应该具有:

final String keyFirstTime = "keyFirstTime";
prefsEditor.putBoolean(keyFirstTime, false);

In Activity 2 you should have: 在活动2中,您应该具有:

boolean firstTime = prefs.getBoolean(keyFirstTime, false); //you don't need the editor
if (firstTime) {
    ...
}

Please go here for a tutorial: https://developer.android.com/training/basics/data-storage/shared-preferences.html 请转到此处获取教程: https : //developer.android.com/training/basics/data-storage/shared-preferences.html

EDIT Try doing this (stolen from here ) 编辑尝试执行此操作(从这里偷走)

private static final String FIRST_RUN = "FIRST_RUN";
SharedPreferences prefs = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    prefs = getSharedPreferences(getApplicationContext().getPackageName(), MODE_PRIVATE);
}

@Override
protected void onResume() {
    super.onResume();

    if (prefs.getBoolean(FIRST_RUN, true)) {           
        prefs.edit().putBoolean(FIRST_RUN, false).commit();
        //call relevant function for first run
    } else {
        //call relevant function for every other run
    }
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();  prefs.edit().putBoolean("keyFirstTime", true).commit();

Now to get Boolean value you have to use 现在要获取布尔值,您必须使用

Boolean check = prefs.getBoolean("keyFirstTime", false);

Now you can check this way 现在您可以检查这种方式

if(check){ your code here } if(check){您的代码在这里}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM