devunwired / recyclerview-playground

Examples of RecyclerView use and custom LayoutManager implementations
MIT License
1.24k stars 269 forks source link

In custom LayoutManager (extends RecyclerView.LayoutManager) RecyclerView.getChildViewHolderInt NullPointerException issue #5

Closed chijikpijik closed 10 years ago

chijikpijik commented 10 years ago

Hi! After trying similar to this (simplify version):

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
     ....
     addView(new TextView(mRecyclerView.getContext()))
}

I have an exception:

java.lang.NullPointerException
    at android.support.v7.widget.RecyclerView.getChildViewHolderInt(RecyclerView.java:2497)
    at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:4807)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:4803)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:4791)

I can't add to RecyclerView child view without ViewHolder?

devunwired commented 10 years ago

Correct. New children should never be added to a RecyclerView directly in the layout manager. The views it adds should always be obtained from the attached RecyclerView.Adapter, so that they are properly accounted for and have a valid ViewHolder attached.

byvlstr commented 7 years ago

Hi, I am facing the same problem, but I obtained the view from the adapter, like this: for (int i = 0; i < getItemCount(); i++){ View newBadge = recycler.getViewForPosition(i); } Thanks for your help!

Error: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.isRemoved()' on a null object reference