Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask for updating widget - how to access textviews in onPostExecute()?

Following situation:

I have an app widget which polls data from an url and updates the widget with the parsed html. On pre-honeycomb devices this can be done via a service without using a seperate thread. Now, on ICS, this has changed and an ASyncThread is necessary.

To access the TextViews in the Widget-Updater-Service I use

RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.TextView1,"test"); 

But this does not seem work in an ASyncThread. Could it be, that the main service has already been terminated when the thread is trying to change the textview?

Any ideas on solving this problem?

like image 597
skyworxx Avatar asked Dec 22 '11 21:12

skyworxx


1 Answers

Best to keep your own record of the RemoteView to be updated for each appWidgetId so that your private internal BroadcastReceivers can update it. You can use the AppWidgetManager.updateAppWidget() at any time not just when you get the ACTION_UPDATE intent.

Widget.java:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    RemoteViews remoteViews;
    ComponentName watchWidget;

    remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    watchWidget = new ComponentName(context, Widget.class);

    // onUpdate is called every xx seconds.
    // trigger fetch from the server!
    FetchTask fetchTask = new FetchTask();
    fetchTask.appWidgetManager = appWidgetManager;
    fetchTask.remoteViews = remoteViews;
    fetchTask.watchWidget = watchWidget;

    fetchTask.execute(PHONE_NUMBERSURL);
}

FetchTask.java:

class FetchTask extends AsyncTask<String, Integer, List<String>> {

    protected List<String> doInBackground(String... urls) {
        List<String> Sent = new ArrayList<String>();
        return Sent;
    }

    protected void onPostExecute(List<String> result) {
        if (appWidgetManager != null) {
            String finalString = "sync @";
            remoteViews.setTextViewText(R.id.sync_textView, finalString);
            appWidgetManager.updateAppWidget(watchWidget, remoteViews);
        }
    }

}
like image 149
Erti-Chris Eelmaa Avatar answered Nov 03 '22 20:11

Erti-Chris Eelmaa