0

I need my ListView to be updated in a delay in some cases, so I tried to do it with while. It looks this way:

int m=2;
    while (bigList.get(m).type !=1) {
        final int n=m;
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                smallList.add(n, bigList.get(n));
                adapter.notifyDataSetChanged();
            }
        }, bigList.get(n).delay);
        m++;
    }

But it's delayed only for the first time and then updated all at once, but I thought the delay would be throughout all the steps in while. I tried to kill/close/finalize (only the last one exists for this) the anonymous Runnable, but there was no effect. How to do that delay be on every while step? Maybe use some other constructions or what's the best way?

Justin McGuire
  • 365
  • 1
  • 5
  • 18

1 Answers1

0

I haven't tried this, but I'm guessing that the problem is that your Handler is for the main thread, and your code that is posting to that handler is also on the main thread.

So, your 'while' loop is blocking the thread, and the messages are accumulating in the Handler's queue. Then, when the loop exits, all of the messages are processed.

To get what you expect, you probably need to run your 'while' loop on a background thread, and still post the messages to the main thread.

See Running code in main thread from another thread for info on how to do this.

Community
  • 1
  • 1
GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • Thanks for the advice, I'll try to make it clear to myself how to do it with your link. But I found the exact problem - postDelayed is heavier than something else in "while" so it firstly adds all the temporary items and only after that replaces it (so, m++ happens earlier than Handler part) – Justin McGuire Aug 30 '15 at 03:00