Загрузка response.body () в адаптер RecyclerView (retrofit2) - PullRequest
0 голосов
/ 15 апреля 2020

ОБНОВЛЕНИЕ: Я получил его на работу после проб и ошибок и некоторых подсказок из комментария ниже.

Изменения сделаны на моем onResponse, MatchHistoryList класс и DotaMatchHistoryAdapter()

enter image description here


Мне трудно понять, как отобразить эти глубоко вложенные JSON массив / объект в Recycler View (TextView) и что надеть onResponse ().

Я думаю, что у меня правильно настроена модель, но у меня есть сомнения по поводу того, как я настроил свой модифицированный экземпляр.

Основная активность

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val service = RetrofitClientInstance.retrofitInstance?.create(GetMatchHistoryService::class.java)
        val call = service?.getAllMatchHistory()
        call?.enqueue(object : Callback<MatchHistoryList>{
            override fun onFailure(call: Call<MatchHistoryList>, t: Throwable) {
                println("Failed to parse because ${t.fillInStackTrace()}")

            }

            override fun onResponse(call: Call<MatchHistoryList>, response: Response<MatchHistoryList>
            ) {
                println("Parse OK")
                //val result = response?.body()
                // you can then pass this to your adapter as list
                val result: List<MatchHistoryModel.Result.Matches> = response?.body()?.result!!.matches



            }
        })

    }
}

Модель:

data class MatchHistoryModel(
    val result: Result
    //val match: Result.Matches,
    //val player: Result.Matches.Player
) {
    data class Result(
        val matches: List<Matches>,
        val num_results: Int,
        val results_remaining: Int,

        @SerializedName("status")
        val status: Int = 0,
        val total_results: Int
    ) {
        data class Matches(
            val dire_team_id: Int,
            val lobby_type: Int,
            val match_id: Long,
            val match_seq_num: Long,
            val players: List<Player>,
            val radiant_team_id: Int,
            val start_time: Int
        ) {
            data class Player(
                @SerializedName("account_id")
                val account_id: Long,
                val hero_id: Int,
                val player_slot: Int
            )
        }
    }
}

MatchHistoryList

data class MatchHistoryList(var result: MatchHistoryModel.Result
//MatchHistoryModel
) {
}

Адаптер:

class DotaMatchHistoryAdapter: RecyclerView.Adapter<DotaMatchHistoryAdapter.ViewHolder>() {

    //var data: List<MatchHistoryModel> = ArrayList()
    var data: List<MatchHistoryModel.Result.Matches> = ArrayList()


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

    override fun getItemCount() = data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])

    fun swapData(data: List<MatchHistoryModel>) {
        this.data = data
        notifyDataSetChanged()
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(item: MatchHistoryModel) = with(itemView) {
            itemView.testView.text = item.result.status.toString()



            // TODO: Bind the data with View
            setOnClickListener {
                // TODO: Handle on click
            }
        }
    }
}

result = response ?. выход body (): response?.body()

JSON расположен здесь.

...