I have succeeded pulling JSON from Reddit API but I cannot put it into my RecyclerView. I set a Log to check if my JSON is empty or null, and the Log successfully print the desired output, so that means my JSON is not empty and contains the necessary data.
Here is my PostRowAdapter.kt
class PostRowAdapter(private val viewModel: MainViewModel)
: ListAdapter<RedditPost, PostRowAdapter.VH>(RedditDiff()) {
private var awwRow = listOf<RedditPost>()
override fun onBindViewHolder(holder: VH, position: Int) {
val binding = holder.binding
awwRow[position].let{
binding.title.text = it.title
}
}
override fun getItemCount() = awwRow.size
}
I thought my code was correct, but when I ran the app, the RecyclerView still blank. Where am I wrong?
your PostRowAdapter
is populating awwRow
list, which is empty on start and never updated, thus this RecyclerView
will always contain 0 elements
if you are using ListAdapter
and submitList(...)
method then you shouldn't override getItemCount
and you shouldn't have own data list, so remove these lines
private var awwRow = listOf<RedditPost>() // on top
override fun getItemCount() = awwRow.size // on bottom
if you want access to whole list set with submitList()
method then you can call inside adapter getCurrentList()
. if you need a particular item at position (like in onBindViewHolder
) then use getItem(position)
. So instead of
awwRow[position].let{
you should have
getItem(position).let{