2

How can I constantly update list items in a list view in Android?

I have an activity that monitors the progress of ongoing transactions. When I load the progress view it captures the state at the moment of creation, but naturally I want to update it.

I tried following this answer, but this creates a code block which is executed constantly even if the activity is not in focus.

Perhaps there is some kind of dynamic list view adaptor that I am unaware of?

Community
  • 1
  • 1
jsj
  • 9,019
  • 17
  • 58
  • 103

1 Answers1

3

The linked answer is mostly fine, just tweak it a little bit to prevent it running after onPause():

private boolean mRunning;

Handler mHandler = new Handler();

Runnable mUpdater = new Runnable() {
    @Override
    public void run() {
        // check if still in focus
        if (!mRunning) return;

        // upadte your list view

        // schedule next run
        mHandler.postDelayed(this, 500); // set time here to refresh views
    }
};

@Override
protected void onResume() {
    super.onResume();
    mRunning = true;
    // start first run by hand
    mHandler.post(mUpdater);
}

@Override
protected void onPause() {
    super.onPause();
    mRunning= false;
}
flx
  • 14,146
  • 11
  • 55
  • 70
  • Okay great.. I just have one doubt: Won't this mean that the `run` method is being constantly called and returned from? – jsj Sep 17 '13 at 03:45
  • 1
    No, it's only run again, if you call some kind of `Handler.post()` method. Returning within the `run()` will result in having no next execution scheduled because you return **before** `mHandler.postDelayed()`. – flx Sep 17 '13 at 03:49
  • Quick question: where do I put this? Is it inside the ListActivity/ListFragment or the Adapter? – adrianmcli Jun 06 '14 at 12:50
  • It's inside the `Activity`/`Fragment`. – flx Jun 10 '14 at 11:10