Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference when doing recyclerView.addView

Why when I tried to add additional view to recyclerView after recyclerView.setAdapter()

return this error

Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference

Example Code

...
recyclerView.setAdapter(mAdapter);

TextView textView = new TextView(this);
textView.setText("TEST");

recyclerView.addView(textView);

The additional view is different compared with view that already displayed in recyclerView. But the additional view that I want to add should be showing at the end of the recyclerview right?

like image 537
j.elmer Avatar asked Nov 19 '16 16:11

j.elmer


2 Answers

I think, the problem is:

You have set the adapter of recyclerview to the adapter that you have made with the class

Adapters: An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

So your adapter view has already provided the view to your recyclerView items.

Now when you are trying to insert an item that is out of context of the view that adapter has provided, it shows an error that your view might not have the same context as adapter's.

So it is not accepting textView in your recyclerView as it should be in the form of cardview that your adapter class is providing.

like image 129
Swr7der Avatar answered Oct 17 '22 09:10

Swr7der


This error occur, because RecyclerView creates its own views (see .onCreateViewHolder() method) - it manages views itself, you cannot add view like that. RecyclerView (that's why it called so) reuses inflated views so it don't have to create new view every time. You should add some data object and bind that object in ViewHolder implementation

like image 33
Alex Shutov Avatar answered Oct 17 '22 08:10

Alex Shutov