Home > Enterprise >  How can i change the code so mListener can be nullable?
How can i change the code so mListener can be nullable?

Time:04-10

So, my problem is i need to initialize mListener with my current code, how can i make it nullable?

class TaskRecycleAdapter: RecyclerView.Adapter<TaskRecycleAdapter.MyViewHolder>() {

    private var list = emptyList<Data>()

    private lateinit var mListener : OnItemClickListener


     class MyViewHolder(binding: TaskHolderBinding, listener: OnItemClickListener): RecyclerView.ViewHolder(binding.root) {

        init {

            itemView.setOnClickListener {

                listener.onItemClick(adapterPosition)

            }

        }
    }



    interface OnItemClickListener {

        fun onItemClick(position: Int)

    }

    fun setOnItemClickListener(listener: OnItemClickListener) {

        mListener = listener

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(TaskHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false), mListener)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

        val item = list[position]

        holder.itemView.findViewById<CheckBox>(R.id.checkBox)
        holder.itemView.findViewById<TextView>(R.id.task).text = item.task
        holder.itemView.findViewById<TextView>(R.id.taskDescription).text = item.task_Details
    }

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

    fun setData(newList: List<Data>) {
        val diffUtil = DiffUtil(list, newList )
        val diffResults = calculateDiff(diffUtil)
        list = newList
        diffResults.dispatchUpdatesTo(this)
    }
    fun getTaskAt(position: Int): Data {
        return list[position]
    }
}

CodePudding user response:

Instead of lateinit you need to use OnItemClickListener?

private var mListener: OnItemClickListener? = null

Then make changes to recieve the nullable listener:

fun setOnItemClickListener(listener: OnItemClickListener?) {
        mListener = listener
    }


 class MyViewHolder(binding: TaskHolderBinding, listener: OnItemClickListener?) :
        RecyclerView.ViewHolder(binding.root) {

        init {

            itemView.setOnClickListener {

                // use safe call for nullables
                listener?.onItemClick(adapterPosition)

            }

        }
    }
  • Related