javaandroidandroid-recyclerviewandroid-thread

How can I inform the RecyclerView that data has changed from within a Timer inside the Adapter


I have a RecyclerView where you can swipe left items to archive them. It would first show the undo layout then after 2 seconds it will be archived (now for a first test I just delete the item). The problem is that using notifyItemRemoved(pos) from a Timer thread crashes the app saying that only the original thread that created the view (UI thread) could touch its views. Is there any trick to go around this? I use the timer inside the ViewHolder of my RecyclerView.Adapter extended class.

Here's the code of the timer:

archiveTimer.schedule(new TimerTask() {
    @Override
    public void run() {
        notesController.remove(position);
        notesList.remove(position);
        queuedForArchive = false;
    }
}, 2000);

On activities you can use runOnUiThread but I can't use that either (function MainActivity.runOnUiThread(Runnable) is not static so I can't use it outside MainActivity)


Solution

  • I found a really tricky way of making timed events happen on UI thread without using a timer. I noticed that all animators are actually timed and you can impl onAnimationEnd on any Animator you want, so I made an ObjectAnimator that changes alpha of an invisible view from 1 to 1 (no change) and set its duration to 2000ms that I needed. I used the same code I wanted to use in the timer inside onAnimationEnd() of that Animator and it worked!!! All code was run on UI thread and changes to other layouts did not create any crashes!