This is my code of RecyclerView for Booking History and Im getting "java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)" exception.
package com.example.bookinghistory;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<User> list;
public MyAdapter(Context context, ArrayList<User> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
User user = list.get(position);
holder.Name.setText(user.getName());
holder.Surname.setText(user.getSurname());
holder.Date.setText(user.getDate());
holder.Contact.setText(user.getContact());
}
@Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Name, Surname, Date, Contact;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
Name = itemView.findViewById(R.id.tvname);
Surname = itemView.findViewById(R.id.tvsurname);
Date = itemView.findViewById(R.id.tvdate);
Contact = itemView.findViewById(R.id.tvcontact);
}
}
}
Changed View v = LayoutInflater.from(context).inflate(R.layout.item,parent);
to View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
But still it didnt work.
You may not set the context for your adapter that case you the error:
LayoutInflater.from(context).......
For Activity
MyAdapter myAdapter = new MyAdapter(userList, this);
For Fragment
MyAdapter myAdapter = new MyAdapter(userList, requireContext());
But that's not the best practice
Here with simple and shorter
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}