J. K. J. K. - 6 months ago 40
Android Question

Passing a null view to RecyclerView.ViewHolder crashes the app when calling super

Since I am creating my views programmatically for my

RecyclerView.ViewHolder
I don't need to pass any view to it in
onCreateViewHolder
but when it calls through to super it crashes with this error:

IllegalArgumentException: itemView may not be null


Here is some code:

@Override
public ImagePreviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ImagePreviewViewHolder(null);
}


protected class ImagePreviewViewHolder extends RecyclerView.ViewHolder {
public LinearLayout page;
public ImageView imageView;

public ImagePreviewViewHolder(View itemView) {
super(itemView); // HERE IT CRASHES
page = createPage();
imageView = createImageView();
page.addView(imageView);
}
}


@DanailAlexiev, is this what you meant:

@Override
public ImagePreviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout page = createPage();
ImageView imageView = createImageView();
page.addView(imageView);
return new ImagePreviewViewHolder(page);
}

protected class ImagePreviewViewHolder extends RecyclerView.ViewHolder {

LinearLayout page;
ImageView imageView;

public ImagePreviewViewHolder(View itemView) {
super(itemView);
page = (LinearLayout) itemView;
imageView = (ImageView) page.getChildAt(0);
}
}

Answer

The ViewHolder uses the itemView reference internally. It can't be null.

What you should do is move your view creation logic to onCreateViewHolder() and pass the created view to your ViewHolder instance.