带有 API 和 JSON Android Studio 的 RecyclerView 无法获取所有数据

问题描述 投票:0回答:1

我面临一个问题,我当前获取的所有数据仅显示一项,而不是使用 recyclerview 和 GSON 的多项,你们能帮我解决这个问题吗?

这是电影适配器:

package com.example.challenge5binar

import android.view.LayoutInflater
import android.view.View.OnClickListener
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.challenge5binar.databinding.ItemRowBinding

class MovieAdapter(
    private val onItemClick: OnClickListener)
    :RecyclerView.Adapter<MovieAdapter.ViewHolder>(){

    private val diffCallBack = object : DiffUtil.ItemCallback<AllResponseTrending>(){
        override fun areContentsTheSame(oldItem: AllResponseTrending, newItem: AllResponseTrending): Boolean = oldItem.hashCode() == newItem.hashCode()
        override fun areItemsTheSame(oldItem: AllResponseTrending, newItem: AllResponseTrending): Boolean{
            return oldItem.results == newItem.results
        }
    }

    fun submitData(value: List<AllResponseTrending>?) = differ.submitList(value)

    private val differ = AsyncListDiffer(this, diffCallBack)

    inner class ViewHolder(private val binding: ItemRowBinding)
        : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: AllResponseTrending){
            binding.apply {
                val result = data.results
                val listtitle = ArrayList<String>()
                val listoverview = ArrayList<String>()
                for (elemen in result){
                    listtitle.add(elemen.name)
                    listoverview.add(elemen.overview)
                }
                tvJudul.text = listtitle.toString()
                tvDeskripsi.text = listoverview.toString()
                
                root.setOnClickListener{
                    onItemClick.onClickItem(data)
                }
            }
        }
    }

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

    override fun onBindViewHolder(holder: MovieAdapter.ViewHolder, position: Int) {
        val data = differ.currentList[position]
        data.let { holder.bind(data) }

    }

    override fun getItemCount(): Int = differ.currentList.size

    interface OnClickListener{
        fun onClickItem(data: AllResponseTrending)
    }
}

这是主页

package com.example.challenge5binar

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.challenge5binar.databinding.FragmentHomeBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class HomeFragment : Fragment(), MovieAdapter.OnClickListener {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentHomeBinding.inflate(inflater, container, false)

        return binding.root
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment HomeFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            HomeFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.ivPerson.setOnClickListener(){
            val bundle = Bundle()
            val usernamehome = arguments?.getString("username")
            bundle.putString("username",usernamehome)
            it.findNavController().navigate(R.id.action_homeFragment_to_profileFragment,bundle)
        }

        binding.rvHomepage.setOnClickListener(){
            it.findNavController().navigate(R.id.action_homeFragment_to_detailFragment)
        }
        binding.rvHomepage.apply {
            layoutManager =LinearLayoutManager(activity)
            adapter = MovieAdapter(this@HomeFragment)
        }

        fetchAllData()
    }

    override fun onClickItem(data: AllResponseTrending) {
        val bundle = Bundle()
        view?.findNavController()?.navigate(R.id.action_homeFragment_to_detailFragment)
    }

    private fun fetchAllData() {
        ApiConfig.getApiService().getAllTrending("day").enqueue(object : Callback<AllResponseTrending> {
            override fun onResponse(
                call: Call<AllResponseTrending>,
                response: Response<AllResponseTrending>
            ) {
                val body = response.body()
                val code = response.code()
                if (code == 200) {
                    showList(body)

                }
            }

            override fun onFailure(call: Call<AllResponseTrending>, t: Throwable) {
                Log.d("MainActivity", "onFailure: ${t.message}")
            }
        })
    }


    private fun showList(data: AllResponseTrending?){
        val adapter = MovieAdapter(this)
        if(data != null){
            adapter.submitData(listOf(data))
        }
        binding.rvHomepage.adapter = adapter
    }
}

这是.kt 文件

package com.example.challenge5binar

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

@Parcelize
data class AllResponseTrending(

    @field:SerializedName("page")
    val page: Int,

    @field:SerializedName("total_pages")
    val totalPages: Int,

    @field:SerializedName("results")
    val results: List<ResultsItem>,

    @field:SerializedName("total_results")
    val totalResults: Int
) : Parcelable

@Parcelize
data class ResultsItem(

    @field:SerializedName("overview")
    val overview: String,

    @field:SerializedName("original_language")
    val originalLanguage: String,

    @field:SerializedName("original_title")
    val originalTitle: String,

    @field:SerializedName("video")
    val video: Boolean,

    @field:SerializedName("title")
    val title: String,

    @field:SerializedName("genre_ids")
    val genreIds: List<Int>,

    @field:SerializedName("poster_path")
    val posterPath: String,

    @field:SerializedName("backdrop_path")
    val backdropPath: String,

    @field:SerializedName("media_type")
    val mediaType: String,

    @field:SerializedName("release_date")
    val releaseDate: String,

    @field:SerializedName("popularity")
    val popularity: String,

    @field:SerializedName("vote_average")
    val voteAverage: String,

    @field:SerializedName("id")
    val id: Int,

    @field:SerializedName("adult")
    val adult: Boolean,

    @field:SerializedName("vote_count")
    val voteCount: Int,

    @field:SerializedName("first_air_date")
    val firstAirDate: String,

    @field:SerializedName("origin_country")
    val originCountry: List<String>,

    @field:SerializedName("original_name")
    val originalName: String,

    @field:SerializedName("name")
    val name: String
) : Parcelable

这是 ApiConfig 和 ApiService

package com.example.challenge5binar

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class ApiConfig {
    companion object{
        fun getApiService(): ApiService {
            val loggingInterceptor =
                HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
            val client = OkHttpClient.Builder()
                .addInterceptor { chain ->
                    val originalRequest = chain.request()
                    val requestBuilder = originalRequest.newBuilder()
                        .header("accept", "application/json")
                        .header("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJjOGFkZmVjYWU3NzljYTJkOGQzMzY3OGIzNDg4OThjYSIsInN1YiI6IjY1NGIzNTJhNjdiNjEzMDEwMmUxODBmMiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.mG3cl5FlagSoKa5k1cUeXMyQuSIm0N9_zpQ4mbGICoI")
                        .method(originalRequest.method, originalRequest.body)
                    val request = requestBuilder.build()
                    chain.proceed(request)
                }
                .addInterceptor(loggingInterceptor)
                .build()
            val retrofit = Retrofit.Builder()
                .baseUrl("https://api.themoviedb.org/3/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()
            return retrofit.create(ApiService::class.java)
        }
    }
}
package com.example.challenge5binar

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query

interface ApiService {
    @GET("trending/all/{time_window}")
    fun getAllTrending(
        @Path("time_window") time_window: String,
        @Query("language") language: String = "en-us"
    ):Call<AllResponseTrending>
}

这是Json结构

{
  "page": 1,
  "results": [
    {
      "adult": false,
      "backdrop_path": "/rLb2cwF3Pazuxaj0sRXQ037tGI1.jpg",
      "id": 872585,
      "title": "Oppenheimer",
      "original_language": "en",
      "original_title": "Oppenheimer",
      "overview": "The story of J. Robert Oppenheimer’s role in the development of the atomic bomb during World War II.",
      "poster_path": "/8Gxv8gSFCU0XGDykEGv7zR1n2ua.jpg",
      "media_type": "movie",
      "genre_ids": [
        18,
        36
      ],
      "popularity": 704.491,
      "release_date": "2023-07-19",
      "video": false,
      "vote_average": 8.24,
      "vote_count": 4118
    },
    {
      "adult": false,
      "backdrop_path": "/mRmRE4RknbL7qKALWQDz64hWKPa.jpg",
      "id": 800158,
      "title": "The Killer",
      "original_language": "en",
      "original_title": "The Killer",
      "overview": "After a fateful near-miss, an assassin battles his employers, and himself, on an international manhunt he insists isn't personal.",
      "poster_path": "/e7Jvsry47JJQruuezjU2X1Z6J77.jpg",
      "media_type": "movie",
      "genre_ids": [
        80,
        53
      ],
      "popularity": 137.63,
      "release_date": "2023-10-25",
      "video": false,
      "vote_average": 7.5,
      "vote_count": 109
    },
    {
      "adult": false,
      "backdrop_path": "/q3jHCb4dMfYF6ojikKuHd6LscxC.jpg",
      "id": 84958,
      "name": "Loki",
      "original_language": "en",
      "original_name": "Loki",
      "overview": "After stealing the Tesseract during the events of “Avengers: Endgame,” an alternate version of Loki is brought to the mysterious Time Variance Authority, a bureaucratic organization that exists outside of time and space and monitors the timeline. They give Loki a choice: face being erased from existence due to being a “time variant” or help fix the timeline and stop a greater threat.",
      "poster_path": "/voHUmluYmKyleFkTu3lOXQG702u.jpg",
      "media_type": "tv",
      "genre_ids": [
        18,
        10765
      ],
      "popularity": 3827.66,
      "first_air_date": "2021-06-09",
      "vote_average": 8.169,
      "vote_count": 10553,
      "origin_country": [
        "US"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/feSiISwgEpVzR1v3zv2n2AU4ANJ.jpg",
      "id": 609681,
      "title": "The Marvels",
      "original_language": "en",
      "original_title": "The Marvels",
      "overview": "Carol Danvers, aka Captain Marvel, has reclaimed her identity from the tyrannical Kree and taken revenge on the Supreme Intelligence. But unintended consequences see Carol shouldering the burden of a destabilized universe. When her duties send her to an anomalous wormhole linked to a Kree revolutionary, her powers become entangled with that of Jersey City super-fan Kamala Khan, aka Ms. Marvel, and Carol’s estranged niece, now S.A.B.E.R. astronaut Captain Monica Rambeau. Together, this unlikely trio must team up and learn to work in concert to save the universe.",
      "poster_path": "/tUtgLOESpCx7ue4BaeCTqp3vn1b.jpg",
      "media_type": "movie",
      "genre_ids": [
        28,
        12,
        878
      ],
      "popularity": 1118.064,
      "release_date": "2023-11-08",
      "video": false,
      "vote_average": 6.49,
      "vote_count": 153
    },
    {
      "adult": false,
      "backdrop_path": "/rqbCbjB19amtOtFQbb3K2lgm2zv.jpg",
      "id": 1429,
      "name": "Attack on Titan",
      "original_language": "ja",
      "original_name": "進撃の巨人",
      "overview": "Several hundred years ago, humans were nearly exterminated by Titans. Titans are typically several stories tall, seem to have no intelligence, devour human beings and, worst of all, seem to do it for the pleasure rather than as a food source. A small percentage of humanity survived by walling themselves in a city protected by extremely high walls, even taller than the biggest Titans. Flash forward to the present and the city has not seen a Titan in over 100 years. Teenage boy Eren and his foster sister Mikasa witness something horrific as the city walls are destroyed by a Colossal Titan that appears out of thin air. As the smaller Titans flood the city, the two kids watch in horror as their mother is eaten alive. Eren vows that he will murder every single Titan and take revenge for all of mankind.",
      "poster_path": "/hTP1DtLGFamjfu8WqjnuQdP1n4i.jpg",
      "media_type": "tv",
      "genre_ids": [
        16,
        10765,
        10759
      ],
      "popularity": 307.669,
      "first_air_date": "2013-04-07",
      "vote_average": 8.664,
      "vote_count": 5627,
      "origin_country": [
        "JP"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/7NRGAtu8E4343NSKwhkgmVRDINw.jpg",
      "id": 507089,
      "title": "Five Nights at Freddy's",
      "original_language": "en",
      "original_title": "Five Nights at Freddy's",
      "overview": "Recently fired and desperate for work, a troubled young man named Mike agrees to take a position as a night security guard at an abandoned theme restaurant: Freddy Fazbear's Pizzeria. But he soon discovers that nothing at Freddy's is what it seems.",
      "poster_path": "/j9mH1pr3IahtraTWxVEMANmPSGR.jpg",
      "media_type": "movie",
      "genre_ids": [
        27,
        9648
      ],
      "popularity": 2066.109,
      "release_date": "2023-10-25",
      "video": false,
      "vote_average": 8.116,
      "vote_count": 1895
    },
    {
      "adult": false,
      "backdrop_path": "/vi0TpQbbZ8FWTRBmawbvegMRbtc.jpg",
      "id": 87917,
      "name": "For All Mankind",
      "original_language": "en",
      "original_name": "For All Mankind",
      "overview": "Explore an aspirational world where NASA and the space program remained a priority and a focal point of our hopes and dreams as told through the lives of NASA astronauts, engineers, and their families.",
      "poster_path": "/mNXT1QjRCEasXGH3rHCTQm0A0Su.jpg",
      "media_type": "tv",
      "genre_ids": [
        18,
        10765,
        10768
      ],
      "popularity": 437.025,
      "first_air_date": "2019-11-01",
      "vote_average": 7.7,
      "vote_count": 521,
      "origin_country": [
        "US"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/rb3QQ2TQfJoCpCZlfXBlBbzYy1D.jpg",
      "id": 844416,
      "title": "Rumble Through the Dark",
      "original_language": "en",
      "original_title": "Rumble Through the Dark",
      "overview": "Set in the dark landscape of the Mississippi Delta, where a former bare-knuckle fighter must win one last fight to pay off his debts to the local mob boss and save his childhood home—the stakes nothing less than life or death.",
      "poster_path": "/19UbYIT9WEQS5qSD3BREDxVXk8g.jpg",
      "media_type": "movie",
      "genre_ids": [
        53
      ],
      "popularity": 22.063,
      "release_date": "2023-11-03",
      "video": false,
      "vote_average": 7.7,
      "vote_count": 3
    },
    {
      "adult": false,
      "backdrop_path": "/hb0BeFvZNx2zLGWwuwENOIVeK1U.jpg",
      "id": 792293,
      "title": "Dumb Money",
      "original_language": "en",
      "original_title": "Dumb Money",
      "overview": "Vlogger Keith Gill sinks his life savings into GameStop stock and posts about it. When social media starts blowing up, so do his life and the lives of everyone following him. As a stock tip becomes a movement, everyone gets rich—until the billionaires fight back, and both sides find their worlds turned upside down.",
      "poster_path": "/gbOnTa2eTbCAznHiusxHI5oA78c.jpg",
      "media_type": "movie",
      "genre_ids": [
        35,
        18,
        36
      ],
      "popularity": 203.864,
      "release_date": "2023-09-15",
      "video": false,
      "vote_average": 6.597,
      "vote_count": 67
    },
    {
      "adult": false,
      "backdrop_path": "/6UH52Fmau8RPsMAbQbjwN3wJSCj.jpg",
      "id": 95557,
      "name": "Invincible",
      "original_language": "en",
      "original_name": "Invincible",
      "overview": "Mark Grayson is a normal teenager except for the fact that his father is the most powerful superhero on the planet. Shortly after his seventeenth birthday, Mark begins to develop powers of his own and enters into his father’s tutelage.",
      "poster_path": "/dMOpdkrDC5dQxqNydgKxXjBKyAc.jpg",
      "media_type": "tv",
      "genre_ids": [
        16,
        10765,
        10759,
        18
      ],
      "popularity": 781.607,
      "first_air_date": "2021-03-25",
      "vote_average": 8.7,
      "vote_count": 3817,
      "origin_country": [
        "US"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/kHlX3oqdD4VGaLpB8O78M25KfdS.jpg",
      "id": 945729,
      "title": "A Haunting in Venice",
      "original_language": "en",
      "original_title": "A Haunting in Venice",
      "overview": "Celebrated sleuth Hercule Poirot, now retired and living in self-imposed exile in Venice, reluctantly attends a Halloween séance at a decaying, haunted palazzo. When one of the guests is murdered, the detective is thrust into a sinister world of shadows and secrets.",
      "poster_path": "/1Xgjl22MkAZQUavvOeBqRehrvqO.jpg",
      "media_type": "movie",
      "genre_ids": [
        9648,
        53,
        80
      ],
      "popularity": 286.45,
      "release_date": "2023-09-13",
      "video": false,
      "vote_average": 6.82,
      "vote_count": 1024
    },
    {
      "adult": false,
      "backdrop_path": "/628Dep6AxEtDxjZoGP78TsOxYbK.jpg",
      "id": 575264,
      "title": "Mission: Impossible - Dead Reckoning Part One",
      "original_language": "en",
      "original_title": "Mission: Impossible - Dead Reckoning Part One",
      "overview": "Ethan Hunt and his IMF team embark on their most dangerous mission yet: To track down a terrifying new weapon that threatens all of humanity before it falls into the wrong hands. With control of the future and the world's fate at stake and dark forces from Ethan's past closing in, a deadly race around the globe begins. Confronted by a mysterious, all-powerful enemy, Ethan must consider that nothing can matter more than his mission—not even the lives of those he cares about most.",
      "poster_path": "/NNxYkU70HPurnNCSiCjYAmacwm.jpg",
      "media_type": "movie",
      "genre_ids": [
        28,
        53
      ],
      "popularity": 2645.664,
      "release_date": "2023-07-08",
      "video": false,
      "vote_average": 7.67,
      "vote_count": 2201
    },
    {
      "adult": false,
      "backdrop_path": "/usKCKmo1UcVsz0t3NNbkPXCmyk1.jpg",
      "id": 823395,
      "title": "The Baker",
      "original_language": "en",
      "original_title": "The Baker",
      "overview": "A quiet, stoic man, lives a monk-like existence in self-imposed exile. When his estranged son is killed in a drug deal gone bad, he is left to look after a granddaughter he never knew existed, and he is forced back into a life he tried to put behind him.",
      "poster_path": "/ApRW9CPK83fF4KCXPR00KCzXOjL.jpg",
      "media_type": "movie",
      "genre_ids": [
        28,
        18,
        80,
        53
      ],
      "popularity": 237.465,
      "release_date": "2023-07-27",
      "video": false,
      "vote_average": 6.6,
      "vote_count": 15
    },
    {
      "adult": false,
      "backdrop_path": "/tC78Pck2YCsUAtEdZwuHYUFYtOj.jpg",
      "id": 926393,
      "title": "The Equalizer 3",
      "original_language": "en",
      "original_title": "The Equalizer 3",
      "overview": "Robert McCall finds himself at home in Southern Italy but he discovers his friends are under the control of local crime bosses. As events turn deadly, McCall knows what he has to do: become his friends' protector by taking on the mafia.",
      "poster_path": "/b0Ej6fnXAP8fK75hlyi2jKqdhHz.jpg",
      "media_type": "movie",
      "genre_ids": [
        28,
        53,
        80
      ],
      "popularity": 866.541,
      "release_date": "2023-08-30",
      "video": false,
      "vote_average": 7.415,
      "vote_count": 1504
    },
    {
      "adult": false,
      "backdrop_path": "/5a4JdoFwll5DRtKMe7JLuGQ9yJm.jpg",
      "id": 695721,
      "title": "The Hunger Games: The Ballad of Songbirds & Snakes",
      "original_language": "en",
      "original_title": "The Hunger Games: The Ballad of Songbirds & Snakes",
      "overview": "64 years before he becomes the tyrannical president of Panem, Coriolanus Snow sees a chance for a change in fortunes when he mentors Lucy Gray Baird, the female tribute from District 12.",
      "poster_path": "/mBaXZ95R2OxueZhvQbcEWy2DqyO.jpg",
      "media_type": "movie",
      "genre_ids": [
        28,
        12,
        878
      ],
      "popularity": 180.438,
      "release_date": "2023-11-15",
      "video": false,
      "vote_average": 6.6,
      "vote_count": 5
    },
    {
      "adult": false,
      "backdrop_path": "/yVgW3PW5Xxk4PHCDzd9f31Aejg5.jpg",
      "id": 1022789,
      "title": "Inside Out 2",
      "original_language": "en",
      "original_title": "Inside Out 2",
      "overview": "Teenager Riley's mind headquarters is undergoing a sudden demolition to make room for something entirely unexpected: new Emotions! Joy, Sadness, Anger, Fear and Disgust, who’ve long been running a successful operation by all accounts, aren’t sure how to feel when Anxiety shows up. And it looks like she’s not alone.",
      "poster_path": "/kAPN02qvX7QTQYtBu9wHN6xQySB.jpg",
      "media_type": "movie",
      "genre_ids": [
        16,
        10751,
        18,
        35
      ],
      "popularity": 12.94,
      "release_date": "2024-06-12",
      "video": false,
      "vote_average": 0,
      "vote_count": 0
    },
    {
      "adult": false,
      "backdrop_path": "/gmECX1DvFgdUPjtio2zaL8BPYPu.jpg",
      "id": 95479,
      "name": "Jujutsu Kaisen",
      "original_language": "ja",
      "original_name": "呪術廻戦",
      "overview": "Yuji Itadori is a boy with tremendous physical strength, though he lives a completely ordinary high school life. One day, to save a classmate who has been attacked by curses, he eats the finger of Ryomen Sukuna, taking the curse into his own soul. From then on, he shares one body with Ryomen Sukuna. Guided by the most powerful of sorcerers, Satoru Gojo, Itadori is admitted to Tokyo Jujutsu High School, an organization that fights the curses... and thus begins the heroic tale of a boy who became a curse to exorcise a curse, a life from which he could never turn back.",
      "poster_path": "/hFWP5HkbVEe40hrXgtCeQxoccHE.jpg",
      "media_type": "tv",
      "genre_ids": [
        16,
        10759,
        10765
      ],
      "popularity": 1154.59,
      "first_air_date": "2020-10-03",
      "vote_average": 8.6,
      "vote_count": 2891,
      "origin_country": [
        "JP"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/iAnNhCoBKUXWoTxgmGYrv2Qc8Dm.jpg",
      "id": 213338,
      "name": "The Buccaneers",
      "original_language": "en",
      "original_name": "The Buccaneers",
      "overview": "A group of fun-loving American girls burst onto the scene in tightly corseted 1870s London, kicking off an Anglo-American culture clash. Sent to secure husbands and status, the buccaneers' hearts are set on much more than that.",
      "poster_path": "/y8uWvyxHqD0RyS1NCBpt0nwgWR.jpg",
      "media_type": "tv",
      "genre_ids": [
        18
      ],
      "popularity": 117.307,
      "first_air_date": "2023-11-07",
      "vote_average": 5.833,
      "vote_count": 6,
      "origin_country": [
        "US"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/o6GbGPOddhwjjMuFyToAFq2FcjB.jpg",
      "id": 201076,
      "name": "Culprits",
      "original_language": "en",
      "original_name": "Culprits",
      "overview": "A family man with a secret criminal past reunites with his crew when a killer starts targeting them.",
      "poster_path": "/gOo5KW8NAvtZdX5jdwnCTYTTpjB.jpg",
      "media_type": "tv",
      "genre_ids": [
        80,
        18
      ],
      "popularity": 162.327,
      "first_air_date": "2023-11-08",
      "vote_average": 5.714,
      "vote_count": 7,
      "origin_country": [
        "GB"
      ]
    },
    {
      "adult": false,
      "backdrop_path": "/daGuh4UzHFF8sSHrYHMw0mb2qBt.jpg",
      "id": 205082,
      "name": "Vigilante",
      "original_language": "ko",
      "original_name": "비질란테",
      "overview": "After witnessing his mother's brutal murder as a child, a young man sets on a path of taking justice into his own hands and finds himself assuming the role of a vigilante, correcting the wrongs of repeat offenders.",
      "poster_path": "/lauvBkCZhcZHj5uUwUxwr5GTPps.jpg",
      "media_type": "tv",
      "genre_ids": [
        80,
        10759,
        18
      ],
      "popularity": 105.815,
      "first_air_date": "2023-11-08",
      "vote_average": 8,
      "vote_count": 7,
      "origin_country": [
        "KR"
      ]
    }
  ],
  "total_pages": 1000,
  "total_results": 20000
}

我最接近的想法是使用列表并使用该列表来创建新的 ItemRow,但它最终会出现在一个项目行中,因此它就像一个包含所有概述和名称的大 ItemRow,而不是同一对概述和名称索引

编辑:我尝试使用 ResultsItem 而不是 AllResponseItem,但它仍然失败

android json kotlin android-recyclerview
1个回答
0
投票

您在适配器中传递

List<AllResponseTrending>
是错误的,请将其更改为
List<ResultsItem>
,因为从 API 响应中您将获得包含
AllResponseTrending
List<ResultsItem>
对象,并且
List<ResultsItem>
将用于在适配器中显示内容。

为此,您必须相应地更改适配器

fun submitData
ViewHolder
中的数据类型。

您应该在适配器中为submitData函数传递

data.results
,并且适配器ViewHolder每行都有
ResultsItem
数据。

更新

private fun showList(data: AllResponseTrending?)
如下

private fun showList(data: AllResponseTrending?){
    val adapter = MovieAdapter(this)
    if(data != null){
        adapter.submitData(data.results)
    }
    binding.rvHomepage.adapter = adapter
}

更新submitData中的参数类型后,您必须将

List<AllResponseTrending>
替换为
List<ResultsItem>

希望它能帮助解决您在

RecyclerView

中仅显示一项的问题
© www.soinside.com 2019 - 2024. All rights reserved.