KaliMa KaliMa - 24 days ago 8
Android Question

Trying to wait a bit and then refresh the adapter

In my RecyclerView there are default animations that play when you remove, add, or change items.

However, performing additional alterations to the items is annoying, because sometimes it doesn't quite update in time if it still thinks the RecyclerView is in the middle of an animation.

So I wanted to have it wait for a bit and then call a final update to the adapter to really make sure those changes are made.

I tried this:

new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
refreshAdapter();
}
});
}
}).run();


However for some reason the sleep command still seems to be occupying the main thread! I launch this after pressing OK on a DialogFragment and it just hangs there for a second before it moves forward with anything, and by the time it does, it doesn't do any of the animations and jumps straight to the final result.

How do I fix this?

Answer

The issue is you're calling run() on your Thread and not start().

Alternatively, you could use Handler's postDelayed(Runnable, long) from the main Thread to achieve what you're trying to do in less code:

new Handler()
    .postDelayed(new Runnable(){
        public void run(){
            refreshAdapters();
        }
    }, 1000);

Or

new Handler()
    .postDelayed(() -> refreshAdapter(),
        1000);