I'm trying to use two layout for my RecyclerView items and I wrote this code for my purpose. It should change layout in odd and even basis numbers
public class WordListAdaptor extends RecyclerView.Adapter<WordListAdaptor.ViewHolder>{
private Context context;
private List<Word> words;
public int counter = 1;
public WordListAdaptor(Context context, List<Word> words){
this.context = context;
this.words = words;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if ( this.counter % 2 == 0) {
view = LayoutInflater.from(this.context).inflate(R.layout.search_listview_gray, parent, false);
} else{
view = LayoutInflater.from(this.context).inflate(R.layout.search_listview_blue,parent,false);}
this.counter ++;
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if ( this.counter % 2 == 0)
holder.textViewGray.setText(words.get(position).getOrginalWord() + " Pos : " + position);
else
holder.textViewBlue.setText(words.get(position).getOrginalWord() + " Pos : " + position);
}
@Override
public int getItemCount() {
return words.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView textViewBlue;
private TextView textViewGray;
private ImageButton blueItemStar;
private ImageButton grayItemStar;
public ViewHolder(View itemView) {
super(itemView);
textViewBlue = itemView.findViewById(R.id.listView_item_textView_blue);
textViewGray = itemView.findViewById(R.id.listView_item_textView_gray);
blueItemStar = itemView.findViewById(R.id.blue_item_star);
grayItemStar = itemView.findViewById(R.id.gray_item_star);
}
}
}
But for this code, I get this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
for one one layout it is working good but after I add a condition to change layout file, I get error.