Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException - Attempt to invoke virtual method RecyclerView$ViewHolder.shouldIgnore()' on a null object reference

Several developers have reported seeing the following stack trace since upgrading to Android Support 23.2.0:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference     at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2913)     at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1445)     at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:144)     at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:282)     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:821)     at android.view.Choreographer.doCallbacks(Choreographer.java:606)     at android.view.Choreographer.doFrame(Choreographer.java:575)     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:807)     at android.os.Handler.handleCallback(Handler.java:739)     at android.os.Handler.dispatchMessage(Handler.java:95)     at android.os.Looper.loop(Looper.java:145)     at android.app.ActivityThread.main(ActivityThread.java:6895)     at java.lang.reflect.Method.invoke(Native Method)     at java.lang.reflect.Method.invoke(Method.java:372)     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

This occurs when RecyclerView's change animation is enabled and corresponding RecyclerView.Adapter methods notifyItemInserted(), notifyItemRemoved(), etc., are called to indicate that an isolated change was made to the list managed by the adapter (as opposed to a wholesale change, as indicated by notifyDataSetChanged()).

Is this due to a bug in RecyclerView, or are we developers doing something wrong?

like image 743
Mark McClelland Avatar asked Mar 04 '16 00:03

Mark McClelland


1 Answers

In my case the error caused because I was setting a new RecyclerView.LayoutParams into the rootview of an item.

Then I realized that RecyclerView item views actually store their ViewHolders in a custom LayoutParams class. So when I reset the LayoutParams ViewHolder reference is gone forever. Which causes a NullPointerException crash later.

The problem is gone after I stopped setting the RecyclerView.LayoutParams into the item rootView. :)

So. Stop doing that in your ViewHolder:

//DON'T DO THAT RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); itemRoot.setLayoutParams(params); 
like image 75
Evren Ozturk Avatar answered Sep 24 '22 02:09

Evren Ozturk