Search code examples
androidbroadcastreceiversharedpreferencesandroid-appwidget

Values in Sharedpreferences are only available after app is restarted


I'm using an App Widget Configuration Activity for setting up some settings for my widget. When the user confirms, settings are saved to Sharedpreferences by calling saveWidgetConfig(Config). Later when the Broadcast for refreshing the widgets is received (first Alarm is after 1000ms) the configuration is loaded again by calling loadWidgetConfig(id). See simple implementation below.

The Problem now is that even though I

  • call editor.apply() (or commit() - doesn't change anything)

  • don't use static classes => every time I create an object: new WidgetConfiguration(context)

when trying to access the SharedPreferences from my receiver class, it doesn't contain any preference for the given key.

BUT:

  • if I try to access the preference directly after apply/commit, it works - even if I create a new WidgetConfiguration class
  • it also works after I restart the device or run a new version from ecipse

So I think it has something to be with different contexts or that I get different "versions" of the Sharedpreferences. But up to now (more than three hours!!!) I was't able to figure out... :-(

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;
    }

}

Solution

  • you save it with "saved widget id " + KEY_WIDGET_CONFIG + widget.getAppwidgetID()

    and you try to get it with a different key KEY_WIDGET_CONFIG + appwidgetID

    use the same key to get it