Search code examples
androidkotlinandroid-recyclerviewfindviewbyid

findViewById returns null in RecyclerView Adapter


I am creating a recycler view and my reference to the image and text view which am fetching with findViewById returns null.

I have tried to change the ids and severally change the image and text but no avail and I have been debugging all day

Student Row


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="40dp">

    <ImageView
        android:id="@+id/itemImage"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/itemText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Recycling me"
       android:textSize="15sp"/>

</LinearLayout>



Adapter

class StudentListAdapter(val list:ArrayList<Student>, internal var newInstance: onItemClickListener) : RecyclerView.Adapter<StudentListAdapter.StudentViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.activity_student_list, parent, false)
        return StudentViewHolder(view)
    }

    override fun getItemCount(): Int{
        return list.size
    }

    override fun onBindViewHolder(holder:StudentViewHolder, position: Int) {
        holder.title.text = list[position].name
        holder.image.setImageResource(list[position].image)
//        var student = list.get(position)
//        holder.textView?.text = student.name
//        holder.image.setImageResource(student.image)
        holder.itemView.setOnClickListener {
            newInstance.onItemClick(list[position])
        }
    }

    class StudentViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        internal var title: TextView
        internal var image:ImageView

        init{
            image = itemView.findViewById(R.id.itemImage)
            title = itemView.findViewById(R.id.itemText)

        }
    }

Solution

  • You are inflating your Activity. Maybe you need to change to your ViewHolder?

    val view = LayoutInflater.from(parent.context).inflate(R.layout.activity_student_list, parent, false)
    

    And it's should be something like

    val view = LayoutInflater.from(parent.context).inflate(R.layout.student_row, parent, false)