I’m making an android app with Kotlin and compose and I’m using GSON to parse some JSON that I retrieve from an API. The data is then put into a list and returned from the function. I have a composable that should be drawn for each item in the list but the function that returns the list is on a coroutine. Here is what I’ve tried to do to draw them but the app just crashes.
val mutableBricksList = remember { mutableStateOf(listOf<LegoPart>()) }
Button(onClick = {
GlobalScope.launch(Dispatchers.IO) {
val fetchedLegoBricks =
fetchLegoSetBricks("https://rebrickable.com/api/v3/lego/sets/${setNumber}/parts/?key=${BuildConfig.API_KEY}")
if (fetchedLegoBricks != null) {
withContext(Dispatchers.Main) {
mutableBricksList.value = fetchedLegoBricks
}
}
}
}) {
Text("Load Bricks")
}
mutableBricksList.value.forEach { legoPart ->
Brick(
brickNumber = legoPart.part.partNum,
brickName = legoPart.part.name,
imageURL = legoPart.part.partImgUrl
)
println(legoPart.part.name)
}
In case you want it here is the function that returns the list
suspend fun fetchLegoSetBricks(url: String): List<LegoPart>? = withContext(Dispatchers.IO) {
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
try {
val response = client.newCall(request).execute()
val responseBody = response.body?.string()
// Parse JSON using Gson library
val gson = Gson()
val legoResponse = gson.fromJson(responseBody, LegoResponse::class.java)
val legoPartsList = legoResponse.results
legoPartsList
} catch (e: Exception) {
println("Error fetching LEGO parts: $e")
null
}
}
The project is on a public GitHub repo at https://github.com/IAMGeeCee/BrickBox if you want to see all the code.
I’ve tried using LaunchedEffect and having it not be when the button is pressed and just when the composable is drawn but that didn’t work either.
George Clensy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.