How to bind viewmodel to a gridView in android?-ThrowExceptions

Exception or error:

I have a gridView in my activity with a custom adapter class, I cannot figure out how to bindview model to my activity’s gridView.
Here is my gridview adapter:

class ImageAdapter constructor(val mContext: Context, private val resource_layout: Int, private val images: Array<Int>) :
    ArrayAdapter<ImageAdapter.ViewHolder>(mContext, resource_layout) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        val holder : ViewHolder

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(resource_layout, null)
            holder = ViewHolder()
            holder.imageItem = convertView.added_picture
            convertView.tag = holder
        } else {
            holder = convertView.tag as ViewHolder


        return convertView!!

    override fun getCount(): Int {
        return images!!.size

    inner class ViewHolder {
        lateinit var imageItem : ImageView
How to solve:

Take <layout></layout> inside your row file and you can set the variable name of your ViewModel name. Now you can set inflate your view in your getViewHolder in adapter as like below.

mTaskCustomLayoutBinding =
            DataBindingUtil.inflate(inflater, R.layout.task_custom_layout, parent, false)
        return MyViewHolder(this!!.mTaskCustomLayoutBinding!!)

Set binding in your viewholder class

inner class MyViewHolder(val mBinding: TaskCustomLayoutBinding) :

So, you’ll get the object of the binding and set the the data to your views.

Hope It’ll help you 🙂


GridView grid = (GridView) itemView.findViewById(;

Leave a Reply

Your email address will not be published. Required fields are marked *