Search code examples
androidwidgetpreference

Widget: storing user preference


I'm trying to make a widget, for which the user has to provide a name. Based on that name, data is collected and shown. In the widget is a refresh button to refresh this data.

The problem is sharing this name between the configuration class and the AppWidgetProvider class. What I have tried:

  • Just use an EditText in the widget. In the config class, set the name in the EditText, and retrieve it in the AppWidgetProvider class. This doesn't work, because I can't find a way to retrieve the text in the AWP.
  • Use SharedPreferences:

In the config class:

c = SelectWidgetStationActivity.this;

// Getting info about the widget that launched this Activity.
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null)
    awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
prefs.edit().putString("widgetname" + awID, name);
prefs.edit().commit();

In the AWP class:

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) { //ACTION_WIDGET_RECEIVER is the action fired by the refresh button
        this.onUpdate(context, AppWidgetManager.getInstance(context), AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName("com.app.myapp", "com.app.myapp.MyWidgetProvider")));
    }
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

for (int widgetId : appWidgetIds) {
        name = prefs.getString("widgetname" + widgetId, "N/A"));
    //more code

name keeps giving me "N/A". I've checked that awID and widgetId are equal. This is probably due to the fact that I'm using different contexts? (Just guessing here)

So what is a way to solve this problem?

Edit When I'm printing the contexts on screen I get the following:

  • config class: com.app.myapp.WidgetConfigActivity@40774d18

  • AWP class: android.app.ReceiverRestrictedContext@406ad290


Solution

  • Just went through this again out of curiousity and noticed this:

    prefs.edit().putString("widgetname" + awID, name);
    prefs.edit().commit();
    

    This gives you 2 different Editor instances. What you do here is get one editor, put in the preference and leave it alone. Then you get a new (unchanged) editor and just commit it (= no changes are written). Just tested that on a small project, doesn't commit correctly as intended.

    So try to substitute the code with something like this:

    Editor e = prefs.edit();
    e.putString("widgetname" + awID, name);
    e.commit();
    

    or chain the commit in

    prefs.edit().putString("widgetname" + awID, name).commit();