0
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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer and it worked! helped me lots.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.