I have a VerticalGridView
that is using a RecyclerView.Adapter
to populate the elements. I have discovered that the onBindViewHolder()
method does not get called if the potential element is off of the viewport. Unfortunately, this is causing a NullPointerException
from a different method because I am catching a TextView
reference in the onBindViewHolder()
method and passing it to an outside variable for later manipulation.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.txtCategoryName.setText(categories.get(position).getStrCategory());
categories.get(position).setTxtViewReference(viewHolder.txtCategoryDefectTotal);
viewHolder.categoryBoxRoot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(CategoryListItem catItem : categories){
if(catItem.getStrCategory().equals(viewHolder.txtCategoryName.getText())){
int index = Defects.getInstance().getCategories().indexOf(catItem) + 1;
MainInterface.grids.get(index).bringToFront();
MainInterface.grids.get(index).setVisibility(View.VISIBLE);
for(VerticalGridView grid : MainInterface.grids){
int gridIndex = MainInterface.grids.indexOf(grid);
if(gridIndex != index){
grid.setVisibility(View.INVISIBLE);
}
}
break;
}
}
}
});
From what I understand, the reference to the TextView
gets created when the Viewholder
object is instantiated.
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtCategoryName;
public TextView txtCategoryDefectTotal;
public View categoryBoxRoot;
public ViewHolder(View itemView) {
super(itemView);
txtCategoryName = (TextView) itemView.findViewById(R.id.textViewCategoryName);
txtCategoryDefectTotal = (TextView) itemView.findViewById(R.id.textViewCategoryTotalDefects);
categoryBoxRoot = itemView.findViewById(R.id.root_category_box);
}
}
Is there a way to force onBindViewHolder()
to be called on all elements at least one time when the Adapter
is instantiated?
I attempted the suggestions here without any success.
I understand that forcing onBindViewHolder()
on all elements would work against the whole purpose of the RecycleView.Adapter. Thus, I am open to any other suggestions on how I can catch that TextView
reference.
As a temporary fix to this problem, I am able to use a try catch block around the method that generates the NullPointerException
. However, I am concerned that the lack of the reference means I could introduce errors in the future.