Home > Software engineering >  keep get out of IndexOutOfBoundsException when i use retrofit and put that data into a recyclerview
keep get out of IndexOutOfBoundsException when i use retrofit and put that data into a recyclerview

Time:10-30

I am using the mvvm architecture. I first call retrofit to get the data via a view model.

    val retrofit = Retrofit.Builder()
        .baseUrl("http://hp-api.herokuapp.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    val service = retrofit.create(HarryPotterApi::class.java)
    val call = service.staff()

    try {

        call.enqueue(object : Callback<Staff> {

            override fun onResponse(call: Call<Staff>, response: Response<Staff>) {

                println("the response code is "  response.code())
                if (response.code() == 200) {
                    val characterData = response.body()!!
                    test ="response is good"
                    println("response is good   The first name is "   characterData[0].name)

                     pictureList.add(characterData[0].name)
                     actorList.add(characterData[0].name)
                    characterList.add(characterData[0].name)
                    houseList.add(characterData[0].name)


                }
            }
            override fun onFailure(call: Call<Staff>, t: Throwable) {

            }
        })}catch (e: IOException) {

        e.printStackTrace()
    }
}

I then pass in the data into a recycler view in the main activity

fun createRV( pictureList: ArrayList<String?>,  actorList: ArrayList<String>,
              characterList: ArrayList<String?>, houseList: ArrayList<String?>){
    val recyclerview = findViewById<RecyclerView>(R.id.recyclerview)
    recyclerview.layoutManager = LinearLayoutManager(this)
    val data = ArrayList<ItemsViewModel>()
    data.add(ItemsViewModel(R.drawable.ic_launcher_background, actorList[0] ,"fds","gsd"))
    val adapter = RVAdapter(data)
    recyclerview.adapter = adapter
}

My api call does work as i can print out the data.

CodePudding user response:

Can you add the stack trace? but probably its one of those places where you try to access an array or list at index 0, you should check if the array is empty first

CodePudding user response:

Maybe response.body() is null or empty so you should check it and let do stuff

Cause : Retrofit cannot parse data in your data model(Staff)

val characterData = response.body()

if (characterData.isNullOrEmpty()) {
        println("List is null or empty")

    } else {

        pictureList.add(characterData[0].name)
        actorList.add(characterData[0].name)
        characterList.add(characterData[0].name)
        houseList.add(characterData[0].name)
    }
  • Related