2

I have a recycler view and I want to perform click on one of its items.

Here is my code:

mRecyclerView.findViewHolderForAdapterPosition(2).itemView.performClick();

It works fine when the item is visible, but when it is not visible i'm getting a null pointer exception

also i tried scroll to position before perform click but i got same result

Any idea on how to solve this issue?

Antwan
  • 3,777
  • 7
  • 40
  • 61

3 Answers3

8

I have solved my problem with this code

mRecyclerView.getLayoutManager().scrollToPosition(17);

search_list.postDelayed(new Runnable() {
    @Override
    public void run() {
        mRecyclerView.findViewHolderForAdapterPosition(17).itemView.performClick();

    }
}, 50);

There is a slight delay for the viewholder to be created. Thus if the item is clicked before viewholder is created an NPE would occur

Kozmotronik
  • 1,004
  • 1
  • 7
  • 17
Antwan
  • 3,777
  • 7
  • 40
  • 61
  • 1
    Thank you so much, you saved my day. – eyadMhanna Oct 29 '15 at 14:30
  • Using delay is a very unwise choice, you don't know how much time it takes to draw the view, and when the delay time is less than the drawing time, you will get NPE – lazy Oct 07 '20 at 01:26
2

Unfortunately for you, this is working as intended. When a child View is scrolled out of the boundaries of a RecyclerView, the child View is often reused to display another item for another position in the list, hence you will get a null View for the position that is no longer displayed.

What you can do is implement a getItem() on the RecyclerView.Adapter to retrieve the item for that position. Not sure if that satisfies your requirements though.

Some Noob Student
  • 13,592
  • 10
  • 62
  • 100
  • Hey ,thanks man for your response I have to issue her that i was trying to prevent recycler view from reusing its item like what we can do with list view but i didn't find a solution for this , – Antwan Oct 28 '15 at 17:41
  • and i tried tp perform scroll to position before performclick to make the item visible but it didn't works also – Antwan Oct 28 '15 at 17:42
  • could plz clarify me how to implement getitem and return the corrent viewholder for position? – Antwan Oct 28 '15 at 18:37
0

It is recommended to use a listener to wait for the drawing to complete, Then perform the operation you want.

    recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // At this point the layout is complete 
            recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
lazy
  • 138
  • 8