barry
barry

Reputation: 4147

Scheduled Task and Android UI

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.

Upvotes: 1

Views: 2844

Answers (2)

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

Ok so there is a better way to do this. Let's say you're using a CursorAdpater to display things in your ListView. Then every time you update your dataset, you can call notifyChange (from any thread), and all CursorAdapters who have cursors on the particular URI you're updating will update what they display.

I realize you may not be using a CrusorAdapter. But there should be a synonymous way to do this for whatever adapter implementation you're using.

Upvotes: 0

Knickedi
Knickedi

Reputation: 8787

Hint: You don't need to synchronize updateList. It's performed on a single thread anyway.

Example with anonymous instances:

private void setUpPageUpdater() {
    listUpdaterExecuter = new ScheduledThreadPoolExecutor(NUM_LIST_UPDATER_THREADS);
    listUpdaterExecuter.scheduleAtFixedRate(new Runnable() {
        private Runnable update = new Runnable() {
            @Override
            public void run() {
                updateList();
            }
        };

        @Override
        public void run() {
            runOnUiThread(update);
        }
    }, 5, 5, TimeUnit.SECONDS);
}

Upvotes: 3

Related Questions