JSON data not showing in RecyclerView

I have this data from an API that I bind in my adapter to my recycler view but my app doesn't show any of the information it's supposed to show. It does work if I separate the data in lists instead, as in declaring different lists in my adapter for each field I need from the API but I was told that's not a good practice so I'm trying to change it (but now it doesn't seem to work).

I'm not sure why it's not working, any ideas?

This is the API response:

package com.example.newsapp

import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import kotlinx.android.parcel.RawValue

data class NewsResponse (
    @SerializedName("status") var Status: String,
    @SerializedName("totalResults") var totalResults: Int,
    @SerializedName("articles") var Articles: List<ArticlesData>
    )

@Parcelize
data class ArticlesData (
    @SerializedName("source") var Source: @RawValue SourceData,
    @SerializedName("author") var Author: String,
    @SerializedName("title") var Title: String,
    @SerializedName("description") var Description: String,
    @SerializedName("url") var Url: String,
    @SerializedName("urlToImage") var urlToImage: String? =" ",
    @SerializedName("publishedAt") var publishedAt: String,
    @SerializedName("content") var Content: String
) : Parcelable

data class SourceData (
    @SerializedName("name") var Name: String,
)

This is the adapter:

package com.example.newsapp

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.newsapp.databinding.NewsItemBinding
import com.squareup.picasso.Picasso

class RecyclerAdapter (
    private var Articles: List<ArticlesData>
) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>(){

    inner class ViewHolder(
        view: View
    ): RecyclerView.ViewHolder(view){
        private val binding = NewsItemBinding.bind(view)

        val itemTitle: TextView = binding.tvTitle
        val itemImage: ImageView = binding.ivNewsImage

        fun bind(articles: ArticlesData){
            Picasso.get().load(articles.urlToImage).into(binding.ivNewsImage)
        }


        init {
            itemImage.setOnClickListener{
                val intent = Intent(view.context, PostActivity::class.java)
                intent.putExtra("title",itemTitle.text)

                view.context.startActivity(intent)
            }
        }
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(Articles[position])

    }

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

This is the Main activity:

package com.example.newsapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.newsapp.databinding.ActivityMainBinding
import kotlinx.coroutines.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var adapter: RecyclerAdapter

    private val news = mutableListOf<ArticlesData>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        makeAPIRequest()

    }

    private fun initRecyclerView() {
        adapter = RecyclerAdapter(news)
        binding.rvNews.layoutManager = LinearLayoutManager(this)
        binding.rvNews.adapter = adapter
    }


    private fun addToList(source:SourceData, author:String, title:String, description:String,
                          url:String,image:String,date:String,content:String){
        news.add(ArticlesData(source,author,title,description,
            url,image,date,content))
    }

    private fun makeAPIRequest() {

        val api = Retrofit.Builder()
            .baseUrl("https://newsapi.org/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(APIService::class.java)

        GlobalScope.launch(Dispatchers.Main){
            val response = api.getNews()
            val posts = response.body()
            try{
                if (posts != null) {
                    for(art in posts.Articles){
                        Log.i("Main Activity", "Result = $art")
                        art.urlToImage?.let {
                            addToList(art.Source,art.Author,art.Title,
                                art.Description, art.Url, it, art.publishedAt, art.Content)
                        }
                    }
                }
                withContext(Dispatchers.Main){
                    initRecyclerView()
                }
            } catch (e:Exception){
                Log.e("Main Activity", e.toString())
            }
        }
    }

}


Read more here: https://stackoverflow.com/questions/68476783/json-data-not-showing-in-recyclerview

Content Attribution

This content was originally published by satoru at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: