Home > front end >  Parse an Array into a Recycler view from Json with Retrofit
Parse an Array into a Recycler view from Json with Retrofit

Time:05-08

Hello i am practicing my kotlin skills with retrofit and recycler views, and i found this type of data in some JSON i found for my practice

"capital":[
          "Montevideo"

]

I know this is an array, and i was able to parse it to my Recyler View by declaring in my data class that capital is a List like this:

data class Country(

    val name: Name,
    val cioc: String,
    val independent: Boolean,
    val region: String,
    val capital: List<String>
)

data class Name(
    val common: String,
    val official: String,

)

I made things normal in my adapter like this

class CountryAdapter(val countries: List<Country>): RecyclerView.Adapter<CountriesViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CountriesViewHolder {

        val view = LayoutInflater.from(parent.context).inflate(R.layout.recyclerline, parent, false)
        return CountriesViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: CountriesViewHolder, position: Int) {
        return holder.bind(countries[position])

    }
}

class CountriesViewHolder(itemView : View): RecyclerView.ViewHolder(itemView){
    private val officialName: TextView = itemView.findViewById(R.id.titulo)
    private val independent: TextView = itemView.findViewById(R.id.titulo2)
    private val capital: TextView = itemView.findViewById(R.id.titulo3)





    fun bind(country: Country) {

        //Integer.parseInt

      //  val sum = (user.id   user.id).toString()
        officialName.text = country.name.official //user.address.geo.lat   " / "   user.address.geo.lng
        independent.text = "Independent: "   country.independent.toString()
        capital.text = country.capital.toString()


    }

}

However in my Recycler view, the result for the capital is appearing like [Montevideo] instead of just Montevideo. How do i take the [] out from the visual result?

How my recycler appears

Thanks

CodePudding user response:

Change this in fun bind(country: Country):

capital.text = country.capital.toString().drop(1).dropLast(1)

//or

capital.text = country.capital[0]

CodePudding user response:

Capital is a list so doing a toString() on a liste will give you a string of an array like this : "[a,b,c,d,e]".

If you want to print the first item you can just get it and use toString on it : country.capital[0]?.toString(). But be careful if the list is empty it will print the following string : "null"

If you want to print the entire list without the hooks you can use joinToString method like this :

country.capital.joinToString(" ")

The first parameter is the separator, here I simply used a space between each items but you can separate them with any strings.

  • Related