I want to periodically updated a ListView in a ListActivity. I know I can do this easily with an AsyncTask subclass, but out of interest I thought I’d look at using a ScheduledThreadPoolExecutor and the android.app.Activity.runOnUiThread(Runnable action) method.
I release I may be having a ‘senior moment’, but problem is I can only seem to get it to work by nesting runnable, as both ScheduledThreadPoolExecutor.scheduleAtFixedRate and runOnUiThread require a Runnable as a parameter.
Here is my working code:
private void setUpPageUpdater()
{
listUpdaterExecuter = new ScheduledThreadPoolExecutor(NUM_LIST_UPDATER_THREADS);
listUpdaterExecuter.scheduleAtFixedRate(new PageUpdater1(), 5, 5, TimeUnit.SECONDS);
}
class PageUpdater1 implements Runnable
{
@Override
public void run()
{
runOnUiThread(new PageUpdater2());
}
}
class PageUpdater2 implements Runnable
{
@Override
public void run()
{
updateList();
}
}
private synchronized void updateList()
{
pages.clear();
pages.addAll(RetrievedPageProvider.getInstance().getPages());
sortList();
adapter.notifyDataSetChanged();
}
Is there a nicer way to code this?
Thanks in advance.
Hint: You don’t need to synchronize
updateList. It’s performed on a single thread anyway.Example with anonymous instances: