简体   繁体   English

getBoolean 返回 false

[英]getBoolean returning false

I'm writing a program that needs to check for default preference settings and respond accordingly.我正在编写一个需要检查默认首选项设置并做出相应响应的程序。 The getBoolean method is always returning false even though R.xml.preferences has defaultValues set as true.即使 R.xml.preferences 将 defaultValues 设置为 true,getBoolean 方法也始终返回 false。 I've tested preferences.contains(prefKey) and this has returned true.我已经测试过preferences.contains(prefKey)并且返回true。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fullscreen);
    PreferenceManager.setDefaultValues(this, R.xml.preferences, true);

    populate();

}

public void populate() {
  SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

  try {
    for (int x = 0; x < 9; x++) {
      if (preferences.getBoolean(prefKey, false)){
        for (int max = 0; max < 20; max++) {
          System.out.println("this ran"+ max + "times at" + i);
        }
      } else {
        for (int max = 0; max < 20; max++) {
          System.out.println("this Skipped"+ max + "times at" + i);
        }
      }
    }
  } catch (IOException ioe) {

  }
}

It is because of this正是因为这个

 if (preferences.getBoolean(prefKey, false))//your default value here is false

change to改成

if (preferences.getBoolean(prefKey, true))

Try clearing your prefs (in onCreate), before setting defaults:在设置默认值之前,尝试清除您的首选项(在 onCreate 中):

PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);

From the PreferenceManager.setDefaultValues() documentation:PreferenceManager.setDefaultValues()文档:

Note: this will NOT reset preferences back to their default values.注意:这不会将首选项重置为其默认值。 For that functionality, use getDefaultSharedPreferences(Context) and clear it followed by a call to this method with this parameter set to true.对于该功能,请使用 getDefaultSharedPreferences(Context) 并清除它,然后调用此方法并将此参数设置为 true。

Perhaps you have called setDefaultValues previously set prefKey to false.也许您之前调用过setDefaultValuesprefKey设置为 false。 According to the PreferenceManager documentation根据PreferenceManager 文档

Note: this will NOT reset preferences back to their default values.注意:这不会将首选项重置为其默认值。 For that functionality, use getDefaultSharedPreferences(Context) and clear it followed by a call to this method with this parameter set to true.对于该功能,请使用 getDefaultSharedPreferences(Context) 并清除它,然后调用此方法并将此参数设置为 true。

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

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