Stas  Shakirov Stas Shakirov - 1 month ago 15
Android Question

Android abstract classes bad magic nullpointer

I wrote adapter for

RecycledView
which uses 2 types of items. So there are three classes for
ViewHolder
: Base class and 2 it's implementations.

public abstract class AbstractCatalogItemViewHolder extends RecyclerView.ViewHolder {
public WebImageView icon;
...
public AbstractCatalogItemViewHolder(View itemView) {
super(itemView);
}
}

public class CategoryViewHolder extends AbstractCatalogItemViewHolder {
public CategoryViewHolder(View itemView) {
super(itemView);
icon = (WebImageView) itemView.findViewById(R.id.icon);
...
}
}


The problem is that the second icon points on object (
WebImageView
), but first is
null
. How it is possible?

@Override
public void onBindViewHolder(AbstractCatalogItemViewHolder abstractViewHolder,
final int position) {

int type = getItemViewType(position);

WebImageView icon = abstractViewHolder.icon;
WebImageView icon2 = ((CategoryViewHolder) abstractViewHolder).icon;
...
}


enter image description here

onCreateViewHolder:

@Override
public AbstractCatalogItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
int type = getItemViewType(i);

View v = inflater.inflate(
type == TYPE_CATEGORY ?
R.layout.item_category :
R.layout.item_product,
viewGroup, false);

return type == TYPE_CATEGORY ? new CategoryViewHolder(v) : new ProductViewHolder(v);
}

Answer

The int passed into onCreateViewHolder is already the itemType, remove your call to getItemViewType inside of onCreateViewHolder.