I’m creating an app widget that queries data from a database, and uses a content observer to update a label once this data changes. The problem is that when the widget is created, I update the label to the correct value. When the data changes, the content observer correctly registers this, but I can’t get the widget to update. The code looks like this:
//called after the configuration activity is done
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId){
m_appWidgetManager = appWidgetManager;
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
m_account = prefs.getString("account" + appWidgetId, "unknown");
m_label = prefs.getString("label" + appWidgetId, "unknown");
m_context = context;
if (!m_accounts.contains(m_account)){
m_accounts.add(m_account);
m_context.getContentResolver().registerContentObserver(GmailContract.Labels.getLabelsUri(m_account), true,new MyContentObserver(new Handler()));
}
updateViews();
}
In the ContentObserver, I only overwrite the following function:
@Override
public void onChange(boolean selfChange) {
GmailUnreadCounterActivity.updateViews();
super.onChange(selfChange);
}
the updateViews function looks like this (when called from updateAppWidget, it works perfectly, when called from the contentobserver, the widget isn’t updated, despite the value changing)
public static void updateViews(){
System.out.println("Number of widgets:" + m_appWidgetIds.length);
for (int i = 0; i < m_appWidgetIds.length; i++){
SharedPreferences prefs = m_context.getSharedPreferences(PREFS_NAME, 0);
m_account = prefs.getString("account" + m_appWidgetIds[i], "unknown");
m_label = prefs.getString("label" + m_appWidgetIds[i], "unknown");
Cursor c = m_context.getContentResolver().query(GmailContract.Labels.getLabelsUri(m_account),null,null,null,null);
while (c.moveToNext()) {
if (c.getString(c.getColumnIndex(GmailContract.Labels.CANONICAL_NAME)).equals(m_label)){
String line = String.valueOf(c.getInt(c.getColumnIndex(GmailContract.Labels.NUM_UNREAD_CONVERSATIONS)));
remoteViews = new RemoteViews(m_context.getPackageName(), R.layout.main);
remoteViews.setTextViewText(R.id.unread_count,
line);
AppWidgetManager.getInstance(m_context).updateAppWidget(m_appWidgetIds[i], remoteViews);
}
}
}
}
How do you get m_appWidgetIds?
Why do you want to keep it in a for loop and update all the instances. Instead of that use
This will update all the instances of widget.
Use the following code to get the ComponentName
ComponentName provider = new ComponentName(context, YourAppWidgetProvider.class);