title: How to create an app widget with a configuration activity, and update it for the first time?
body: <p>This is driving me crazy. I don't know how to update the app widget from the configuration activity, even with the recommended practises. Why the update method is not called on the app widget creation is beyond my understanding.</p>
  
  <p>What I'd like: an app widget containing a collection (with a listview) of items. But the user needs to select something, so I need a configuration activity.</p>
  
  <p>The configuration activity is a <code>ListActivity</code>:</p>
  
  <pre><code>@TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public class ChecksWidgetConfigureActivity extends SherlockListActivity {
      private List&lt;Long&gt; mRowIDs;
      int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
      private BaseAdapter mAdapter;
  
      @Override
      protected void onCreate(final Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setResult(RESULT_CANCELED);
          setContentView(R.layout.checks_widget_configure);
  
          final Intent intent = getIntent();
          final Bundle extras = intent.getExtras();
          if (extras != null) {
              mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
          }
  
          // If they gave us an intent without the widget id, just bail.
          if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
              finish();
          }
  
          mRowIDs = new ArrayList&lt;Long&gt;(); // it's actually loaded from an ASyncTask, don't worry about that — it works.
          mAdapter = new MyListAdapter((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE));
          getListView().setAdapter(mAdapter);
      }
  
      private class MyListAdapter extends BaseAdapter {
          // not relevant...
      }
  
      @Override
      protected void onListItemClick(final ListView l, final View v, final int position, final long id) {
          if (position &lt; mRowIDs.size()) {
              // Set widget result
              final Intent resultValue = new Intent();
              resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
              resultValue.putExtra("rowId", mRowIDs.get(position));
              setResult(RESULT_OK, resultValue);
  
              // Request widget update
              final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
              ChecksWidgetProvider.updateAppWidget(this, appWidgetManager, mAppWidgetId, mRowIDs);
          }
  
          finish();
      }
  }
  </code></pre>
  
  <p>As you can see I'm calling a static method from my app widget provider. I got that idea from <a href="http://web.archive.org/web/20100814165740/http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/appwidget/ExampleAppWidgetProvider.html" rel="noreferrer">the official doc</a>.</p>
  
  <p>Let's have a look at my provider:</p>
  
  <pre><code>@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  public class ChecksWidgetProvider extends AppWidgetProvider {
      public static final String TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION";
      public static final String EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM";
  
      @Override
      public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
          super.onUpdate(context, appWidgetManager, appWidgetIds);
          final int N = appWidgetIds.length;
  
          // Perform this loop procedure for each App Widget that belongs to this provider
          for (int i = 0; i &lt; N; i++) {
              // Here we setup the intent which points to the StackViewService which will
              // provide the views for this collection.
              final Intent intent = new Intent(context, ChecksWidgetService.class);
              intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
              // When intents are compared, the extras are ignored, so we need to embed the extras
              // into the data so that the extras will not be ignored.
              intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
              final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.checks_widget);
              rv.setRemoteAdapter(android.R.id.list, intent);
  
              // The empty view is displayed when the collection has no items. It should be a sibling
              // of the collection view.
              rv.setEmptyView(android.R.id.list, android.R.id.empty);
  
              // Here we setup the a pending intent template. Individuals items of a collection
              // cannot setup their own pending intents, instead, the collection as a whole can
              // setup a pending intent template, and the individual items can set a fillInIntent
              // to create unique before on an item to item basis.
              final Intent toastIntent = new Intent(context, ChecksWidgetProvider.class);
              toastIntent.setAction(ChecksWidgetProvider.TOAST_ACTION);
              toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
              toastIntent.setData(Uri.parse(toastIntent.toUri(Intent.URI_INTENT_SCHEME)));
              final PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
              rv.setPendingIntentTemplate(android.R.id.list, toastPendingIntent);
  
              appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
          }
      }
  
      @Override
      public void onReceive(final Context context, final Intent intent) {
          final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
          if (intent.getAction().equals(TOAST_ACTION)) {
              final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
              final long rowId = intent.getLongExtra("rowId", 0);
              final int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);
              Toast.makeText(context, "Touched view " + viewIndex + " (rowId: " + rowId + ")", Toast.LENGTH_SHORT).show();
          }
          super.onReceive(context, intent);
      }
  
      @Override
      public void onAppWidgetOptionsChanged(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId, final Bundle newOptions) {
          updateAppWidget(context, appWidgetManager, appWidgetId, newOptions.getLong("rowId"));
      }
  
      public static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId, final long rowId) {
          final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.checks_widget);
          appWidgetManager.updateAppWidget(appWidgetId, views);
      }
  }
  </code></pre>
  
  <p>This is basically a copy/paste from the official doc. We can see my static method here. Let's pretend that it actually uses the <code>rowId</code> for now.</p>
  
  <p>We can also see another failed (see below) attempt to update the app widget when I receive the options changed broadcast (<code>onAppWidgetOptionsChanged</code>).</p>
  
  <p>The <code>Service</code> required for an app widget based on collections is almost an exact copy/paste of the doc:</p>
  
  <pre><code>@TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public class ChecksWidgetService extends RemoteViewsService {
      @Override
      public RemoteViewsFactory onGetViewFactory(final Intent intent) {
          return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
      }
  }
  
  class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
      private static final int mCount = 10;
      private final List&lt;WidgetItem&gt; mWidgetItems = new ArrayList&lt;WidgetItem&gt;();
      private final Context mContext;
      private final int mAppWidgetId;
      private final long mRowId;
  
      public StackRemoteViewsFactory(final Context context, final Intent intent) {
          mContext = context;
          mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
          mRowId = intent.getLongExtra("rowId", 0);
      }
  
      @Override
      public void onCreate() {
          // In onCreate() you setup any connections / cursors to your data source. Heavy lifting,
          // for example downloading or creating content etc, should be deferred to onDataSetChanged()
          // or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.
          for (int i = 0; i &lt; mCount; i++) {
              mWidgetItems.add(new WidgetItem(i + " (rowId: " + mRowId + ") !"));
          }
  
          // We sleep for 3 seconds here to show how the empty view appears in the interim.
          // The empty view is set in the StackWidgetProvider and should be a sibling of the
          // collection view.
          try {
              Thread.sleep(3000);
          } catch (final InterruptedException e) {
              e.printStackTrace();
          }
      }
  
      @Override
      public void onDestroy() {
          // In onDestroy() you should tear down anything that was setup for your data source,
          // eg. cursors, connections, etc.
          mWidgetItems.clear();
      }
  
      @Override
      public int getCount() {
          return mCount;
      }
  
      @Override
      public RemoteViews getViewAt(final int position) {
          // position will always range from 0 to getCount() - 1.
  
          // We construct a remote views item based on our widget item xml file, and set the
          // text based on the position.
          final RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
          rv.setTextViewText(R.id.widget_item, mWidgetItems.get(position).text);
  
          // Next, we set a fill-intent which will be used to fill-in the pending intent template
          // which is set on the collection view in StackWidgetProvider.
          final Bundle extras = new Bundle();
          extras.putInt(ChecksWidgetProvider.EXTRA_ITEM, position);
          final Intent fillInIntent = new Intent();
          fillInIntent.putExtras(extras);
          rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent);
  
          // You can do heaving lifting in here, synchronously. For example, if you need to
          // process an image, fetch something from the network, etc., it is ok to do it here,
          // synchronously. A loading view will show up in lieu of the actual contents in the
          // interim.
          try {
              L.d("Loading view " + position);
              Thread.sleep(500);
          } catch (final InterruptedException e) {
              e.printStackTrace();
          }
  
          // Return the remote views object.
          return rv;
      }
  
      @Override
      public RemoteViews getLoadingView() {
          // You can create a custom loading view (for instance when getViewAt() is slow.) If you
          // return null here, you will get the default loading view.
          return null;
      }
  
      @Override
      public int getViewTypeCount() {
          return 1;
      }
  
      @Override
      public long getItemId(final int position) {
          return position;
      }
  
      @Override
      public boolean hasStableIds() {
          return true;
      }
  
      @Override
      public void onDataSetChanged() {
          // This is triggered when you call AppWidgetManager notifyAppWidgetViewDataChanged
          // on the collection view corresponding to this factory. You can do heaving lifting in
          // here, synchronously. For example, if you need to process an image, fetch something
          // from the network, etc., it is ok to do it here, synchronously. The widget will remain
          // in its current state while work is being done here, so you don't need to worry about
          // locking up the widget.
      }
  }
  </code></pre>
  
  <p>And at last, my widget layout:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/widgetLayout"
      android:orientation="vertical"
      android:padding="@dimen/widget_margin"
      android:layout_width="match_parent"
      android:layout_height="match_parent"&gt;
  
      &lt;TextView
          android:id="@+id/resizeable_widget_title"
          style="@style/show_subTitle"
          android:padding="2dp"
          android:paddingLeft="5dp"
          android:textColor="#FFFFFFFF"
          android:background="@drawable/background_pink_striked_transparent"
          android:text="@string/show_title_key_dates" /&gt;
  
      &lt;ListView
          android:id="@android:id/list"
          android:layout_marginRight="5dp"
          android:layout_marginLeft="5dp"
          android:background="@color/timeline_month_dark"
          android:layout_width="match_parent"
          android:layout_height="match_parent" /&gt;
  
      &lt;TextView
          android:id="@android:id/empty"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:textColor="#ffffff"
          android:textStyle="bold"
          android:text="@string/empty_view_text"
          android:textSize="20sp" /&gt;
  
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p>The relevant section of my android manifest XML file:</p>
  
  <pre><code>&lt;receiver android:name="com.my.full.pkg.ChecksWidgetProvider"&gt;
      &lt;intent-filter&gt;
              &lt;action android:name="android.appwidget.action.APPWIDGET_UPDATE" /&gt;
      &lt;/intent-filter&gt;
  
      &lt;meta-data
              android:name="android.appwidget.provider"
              android:resource="@xml/checks_widget_info" /&gt;
  &lt;/receiver&gt;
  &lt;activity android:name="com.my.full.pkg.ChecksWidgetConfigureActivity"&gt;
      &lt;intent-filter&gt;
              &lt;action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /&gt;
      &lt;/intent-filter&gt;
  &lt;/activity&gt;
  &lt;service
      android:name="com.my.full.pkg.ChecksWidgetService"
      android:permission="android.permission.BIND_REMOTEVIEWS" /&gt;
  </code></pre>
  
  <p><code>xml/checks_widget_info.xml</code>:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;appwidget-provider
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:minWidth="146dp"
      android:minHeight="146dp"
      android:updatePeriodMillis="86400000"
      android:initialLayout="@layout/checks_widget"
      android:configure="com.my.full.pkg.ChecksWidgetConfigureActivity"
      android:resizeMode="horizontal|vertical"
      android:previewImage="@drawable/resizeable_widget_preview" /&gt;
  </code></pre>
  
  <hr>
  
  <p>So, what's wrong? Well, when I create the widget it's empty. I mean void. Empty. Nothing. I don't have the empty view defined in my layout! What the hell?</p>
  
  <p>If I reinstall the app or reboot the device (or kill the launcher app), the app widget is actually updated and contains the 10 items that are automatically added as in the example.</p>
  
  <p>I can't get the damn thing to update after the configuration activity finishes. This sentence, taken from the doc, is beyond me: "<em>The onUpdate() method will not be called when the App Widget is created [...]—it is only skipped the first time.</em>".</p>
  
  <p>My question is:</p>
  
  <ul>
  <li><strike>Why in the world did the Android dev team chose not to call update for the first time the widget is created?</strike></li>
  <li>How can I update my app widget before the configuration activity finishes?</li>
  </ul>
  
  <p>Another thing that I don't understand is the action flow:</p>
  
  <ol>
  <li>Install the app with the last code compiled, prepare space on the launcher, open the "widgets" menu from the launcher</li>
  <li>Choose my widget and place it to the desired area</li>
  <li>At that moment, my app widget provider receives <code>android.appwidget.action.APPWIDGET_ENABLED</code> and then <code>android.appwidget.action.APPWIDGET_UPDATE</code></li>
  <li>Then my app widget provider gets its <code>onUpdate</code> method called. <strong><em>I expected this to happen AFTER the configuration activity finishes...</em></strong></li>
  <li>My configuration activity gets started. But the app widget seems already created AND updated, which I don't understand.</li>
  <li>I choose the item from my configuration activity: <code>onListItemClick</code> gets called</li>
  <li>The static <code>updateAppWidget</code> from my provider is called, desperately trying to update the widget.</li>
  <li>The configuration activity sets its result and finishes.</li>
  <li>The provider receives <code>android.appwidget.action.APPWIDGET_UPDATE_OPTIONS</code>: well, that does make a lot of sense to receive a size update when created. That's where I call desperately <code>updateAppWidget</code></li>
  <li><strong><em><code>onUpdate</code> from my provider is NOT called. Why??!!</em></strong></li>
  </ol>
  
  <p>In the end: the widget is empty. Not listview-empty or @android:id/empty-empty, really <strong><em>EMPTY</em></strong>. No view displayed. Nothing.<br>
  If I install the app again, the app widget is populated with views inside the listview, as expected.<br>
  Resizing the widget has no effect. It just calls <code>onAppWidgetOptionsChanged</code> again, which has no effect.</p>
  
  <p>What I mean by empty: the app widget layout is inflated, but the listview is NOT inflated and the empty view is NOT displayed.</p>