Reputation: 1
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { // <-- line 9
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView textView;
public MyViewHolder(View v) {
super(v);
textView = (TextView) v.findViewById(R.id.mTextView);
this.textView = textView;
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false); // <-- line 36
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.textView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
this is the code of MyAdapter class and when i run it, The app keeps shut down so i have checked Logcat and it says
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.t5online.chat.hanbattalk, PID: 593
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at com.t5online.chat.hanbattalk.MyAdapter.onCreateViewHolder(MyAdapter.java:36)
at com.t5online.chat.hanbattalk.MyAdapter.onCreateViewHolder(MyAdapter.java:9)
However, I can't find what the problem is in line 36 and 9.
Upvotes: 0
Views: 186
Reputation: 1601
You are not inflating view properly in onCreateViewHolder
. It should be something like this ,
View view;
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
view = layoutInflater.inflate(R.layout.my_text_view,parent,false);
return new MyAdapter.MyViewHolder(view);
Upvotes: 1