Search code examples
javaandroidandroid-widgetandroid-appwidget

Why are these state variables in my AppWidgetProvider's onReceive null?


I have variables that I assign to in onUpdate and need to access the value of in onReceive of my app widget provider class.

public class MyWidgetProvider extends AppWidgetProvider {
    private static String name;
    private static SharedPreferences myPrefs;
    private static final String START_ACTION = "start";

    @Override
    public void onUpdate(final Context context, final AppWidgetManager appWidgetManager,
                               final int[] appWidgetIds) {
        views = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
        Intent intent1 = new Intent(context, MyAppWidgetProvider.class);
        providerIntent.setAction(START_ACTION);
        pendingIntent = PendingIntent.getBroadcast(context, 0, providerIntent, 0);
        ....
        myPrefs = Context.getSharedPreferences("PrefsName", 0x0000);
        name = "new name";
        networkClient.requestItem(name, new JsonHandler {
            @Override
            public void requestSuccess(JSONObject resp) {
                views.setOnClickPendingIntent(R.section, pendingIntent);
            }
    }

    @Override 
    public void onReceive(@NonNull final Context context, @NonNull Intent intent) {
        super.onReceive(context, intent);
        if(intent.getAction().equals(START_ACTION)) {
            myPrefs.edit().putString("someKey", name).commit();
        }
    }

I put log messages in onReceive and see that myPrefs and name are both null.

Then I ran it through the debugger:

  1. onUpdate was called, "myPrefs" was initialized a value, then "name" too.
  2. I clicked a section and onReceive was called, where I found myPrefs and name to be null!

I read onUpdate() intilized variable are null in onReceive of widget class and made sure these state variables were static, but they are still null. Why is this, and how do I retain these values in onReceive?


Solution

  • Your process may be terminated in between invocations of onReceive(). If you wish to hold onto data from a BroadcastReceiver, such as an AppWidgetProvider, do so using some persistent data store (database, SharedPreferences, or other sort of file). Static data members are only a cache, nothing more.