【问题标题】:Values in Sharedpreferences are only available after app is restartedSharedpreferences 中的值仅在应用重启后可用
【发布时间】:2014-06-12 15:25:20
【问题描述】:

我正在使用 App Widget Configuration Activity 为我的小部件设置一些设置。当用户确认后,通过调用 saveWidgetConfig(Config) 将设置保存到 Sharedpreferences。稍后当接收到刷新小部件的广播时(第一个警报在 1000 毫秒后),通过调用 loadWidgetConfig(id) 再次加载配置。请参阅下面的简单实现。

现在的问题是,即使我

  • 调用 editor.apply()(或 commit() - 不会改变任何东西)

  • 不要使用静态类 => 每次创建对象时: 新的小部件配置(上下文)

当尝试从我的接收器类访问 SharedPreferences 时,它不包含对给定键的任何偏好。

但是

  • 如果我尝试在应用/提交后直接访问首选项,它可以工作 - 即使我创建了一个新的 WidgetConfiguration 类
  • 在我重新启动设备或从 ecipse 运行新版本后它也可以工作

所以我认为它与不同的上下文有关,或者我得到了 Sharedpreferences 的不同“版本”。但是直到现在(三个多小时!!!)我都无法弄清楚...... :-(

public class WidgetConfiguration {

    private SharedPreferences prefs;
    private String LOG_TAG = this.getClass().getSimpleName();

    public WidgetConfiguration(Context context) {
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static String KEY_WIDGET_CONFIG = "single_widget_object_config_";

    public void saveWidgetConfig(Widget widget) {
        Gson gson = new Gson();
        String json = gson.toJson(widget);
        Editor editor = prefs.edit();
        editor.putString(KEY_WIDGET_CONFIG + widget.getAppwidgetID(), json);
        Log.d(LOG_TAG, "saved widget id " + widget.getAppwidgetID() + "\n" + json);
        editor.apply();
    };

    public Widget loadWidgetConfig(int appwidgetID) {
        Widget loadedWidget = null;
        String key = KEY_WIDGET_CONFIG + appwidgetID;
        if (prefs.contains(key))
        {
            String json = prefs.getString(key, null);
            Log.d(LOG_TAG, "loaded widget id " + appwidgetID + "\n" + json);
            Gson gson = new Gson();
            loadedWidget = gson.fromJson(json, Widget.class);
        }
        else
        {
            Log.e(LOG_TAG, "no preferences found for widget: " + key);
        }

        return loadedWidget;
    }

}

【问题讨论】:

    标签: android broadcastreceiver sharedpreferences android-appwidget


    【解决方案1】:

    放:

    editor.commit();
    

    代替:

    editor.apply();
    

    【讨论】:

      【解决方案2】:

      你保存它 “保存的小部件 ID” + KEY_WIDGET_CONFIG + widget.getAppwidgetID()

      然后您尝试使用不同的密钥获取它 KEY_WIDGET_CONFIG + appwidgetID

      使用相同的密钥获取它

      【讨论】:

      • 哦,是的,这是编辑日志消息时的复制和粘贴错误,但这不是问题的根源。正如我一开始所说,在应用程序完全关闭后 - 它可以工作 - 所以这不是不同键的问题。
      • 而不是 prefs = PreferenceManager.getDefaultSharedPreferences(context);尝试使用 sharedPreferences = mContext.getSharedPreferences("someString", Context.MODE_PRIVATE);并且在放置它们时 sharedPreferences.edit() .putString("someString.key", json)。这是来自我自己的工作代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多