Skip to content Skip to sidebar Skip to footer

Null Pointer Exception When Trying To Programmatically Perform Click On Non Visible Recycler View Item

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

Solution 1:

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

Solution 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.

Solution 3:

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);
        }
    });

Post a Comment for "Null Pointer Exception When Trying To Programmatically Perform Click On Non Visible Recycler View Item"