My RecyclerView is not showing any data Android Studio(Kotlin, ViewBinding)

71 Views Asked by At

I am creating a weather app in which the recycler view is suppose to show today's forecast but is not showing anything. I am also not getting any kind of error in my code.

I have tried everything I could as I am a novice. Below is the code for my Adapter class (https://i.stack.imgur.com/VTxis.png) (https://i.stack.imgur.com/UA10S.png) Below is the main activity function in which I am trying to fetch the data (https://i.stack.imgur.com/6vAyx.png)

2

There are 2 best solutions below

2
Miroslav Hýbler On

There are several issues in your code, you have to fix your viewBinding implementation. I am assuming that:

  • Data from api are correct
  • getItemsCount() returns more than zero:

I will try to explain:

Problem

Problem is probably caused by binding property in Forcastadapter. Now you have one reference of binding which is being redeclared on every 'onCreateViewHolder' call. But in onBindViewHolder you are creating another instance of ForcastViewBinding which is getting updated, but it's not visible.

Solution

There is no reason to keep view binding inside adapter class. Just keep it inside ViewHolder and always use one binding for each viewHolder.

inner class ViewHolder(val binding: ForcastViewBinding): RecyclerView.ViewHolder(binding.root)

Then update onCreateViewHolder:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
   val inflater = LayoutInflater.from(parent.context)
   val binding = ForcastViewBinding.inflate(inflater, parent, false)
   return ViewHolder(binding)
}

And in onBindViewHolder replace:

val binding = ForcastViewBinding.bind(holder.itemView)

with

val binding = holder.binding
1
Dan Riza On

Maybe you shouldn't use the inner ViewHolder class at all, and just return the Viewholder from onCreateViewHolder like this return ViewHolder(binding.root) to give it a view, then it will render, and in onBindViewHolder you can access the view like this holder.itemView.findViewById...

Or more elegant to create your ViewHolder with a binding, and access it in onBindViewHolder with val binding = holder.binding. This will give you access to the views of the binding in onBindViewHolder by using this val myView = binding.someView and from there you can build your list item.