i'm trying to get image from json and load it into xml. and i already get the image url and just have to load it. but whenever i try to load the image it always shows Index 1 out of range [0..1)
error messege but i dont know why it happen.
this is my code
val url = "https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=133616"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback, okhttp3.Callback {
override fun onFailure(call: Call, e: IOException) {
println("failed")
}
override fun onResponse(call: okhttp3.Call?, response: okhttp3.Response?) {
val body = response?.body()?.string()
println(body)
val jsonObject = JSONObject(body)
val jsonArray = jsonObject.getJSONArray("teams")
for (i in 0..jsonArray.length()) {
val jsonObject2 = jsonArray.getJSONObject(i)
val lambang = jsonObject2.getString("strTeamBadge")
Log.v("lambang", "" + lambang)
Picasso.get().load(lambang).into(badge_away)
}
}
})
and when i change the for to while(i<jsonArray.length()
it load the image over and over without stop.
please if you know how to solve this please help
ps: my jsonArray actually only have 1 index
Replace 0..jsonArray.length()
with 0..jsonArray.length()-1
or 0 until jsonArray.length()
array indexes are zero based so the last element has index equal to jsonArray.length()-1
.
When you use 0 until jsonArray.length()
the last value jsonArray.length()
is excluded.
If the array has only 1 element then the for loop should execute just once.
Edit: this is a very useful link for this case Kotlin Ranges