【问题标题】:Preference Manager loads always default value首选项管理器始终加载默认值
【发布时间】:2014-04-29 20:17:10
【问题描述】:

我使用首选项管理器来保存一些整数和布尔值。 我创建了一个 SettingsPreferences 类:

public class SettingsPreferences {

    private Context mContext;

    public SettingsPreferences(Context context) {
        this.mContext = context;
    }

    public boolean isNull() {
        if (PreferenceManager.getDefaultSharedPreferences(mContext) == null) {
            return true;
        } else {
            return false;
        }
    }

    public void setBoolean(String name, boolean value) {
        PreferenceManager.getDefaultSharedPreferences(mContext).edit()
                .putBoolean(name, value).apply();
    }

    public void setInt(String name, int value) {
        PreferenceManager.getDefaultSharedPreferences(mContext).edit()
                .putInt(name, value).apply();
    }

    public boolean getBoolean(String name, boolean defaultValue) {
        return PreferenceManager.getDefaultSharedPreferences(mContext)
                .getBoolean(name, defaultValue);
    }

    public int getInt(String name, int defaultValue) {
        return PreferenceManager.getDefaultSharedPreferences(mContext).getInt(
                name, defaultValue);
    }}

在 Main 类的 onCreate 方法中,我添加了默认值:

mSettingsPreferences = new SettingsPreferences(getApplicationContext());
if(mSettingsPreferences.isNull() == true) {
    mSettingsPreferences.setBoolean("MAX", 1);
    mSettingsPreferences.setBoolean("PROGRESS", 1);
}

在片段类中,我需要加载该数据并将其显示在进度条中。 这是代码:

Thread t = new Thread() {
   public void run() {
     try {
       sleep(100);
       SettingsPreferences sett = new SettingsPreferences(mContext);
       mProgBar.setMax(sett.getInt("MAX", 2));
       mProgBar.setProgress(sett.getInt("PROGRESS", 1));

     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
};
t.start();

上下文是定义的,我检查了他,进度条也是,但每次它加载我的默认值。 有什么问题?

【问题讨论】:

标签: java android default-value


【解决方案1】:

使用这个:

要初始化首选项,请使用:

SharedPreferences preferences = PreferenceManager
        .getDefaultSharedPreferences(context);
String string = preferences.getString(key, defValue);

现在是 Storind 数据:

Editor editor = preferences.edit();
editor.putString(key,value);
editor.commit();

有关更多信息,请参阅tutorial

希望你能理解。

【讨论】:

  • 问题不在于 SettingsPreference 类方法,因为我在其他类中使用相同的方法,它返回我保存的值。
【解决方案2】:

您必须调用 Editor 的 commit() 来应用更改

【讨论】:

    【解决方案3】:

    我想你的 isNull() 总是返回 false,因为:

    PreferenceManager.getDefaultSharedPreferences(mContext)
    

    不会返回null,至少我从未见过这种情况。这样你就永远不会初始化你的 MAX 和 PROGRESS 值,最后你会读取默认值。

    您可以使用 SharedPreferences.contains 方法来检查 MAX 是否存在,如果不存在则初始化它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 2013-11-17
      • 2011-02-11
      • 2013-07-19
      • 2013-06-19
      相关资源
      最近更新 更多