Issue
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?
Thanks
Solution
Capital is a list so doing a toString() on a list 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?.get(0)?.toString()
.
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.
Answered By - Dinamots
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.