Search code examples
androidcastingandroid-jetpack-composeretrofit2

Casting Any to Integer returns a NullPointerException from the API


While getting data from the API, a NullPointerException was thrown because of casting Any to an integer. If someone can tell.

val albums by remember {                                              
         mutableIntStateOf((artistStatsItem!!.albums!!.total!! as? Int)!!) 
}
data class Album(
    @field:SerializedName("created")
    val created: Int? = null,

    @field:SerializedName("total")
    val total: Any? = null,         // <---

    @field:SerializedName("coming")
    val coming: Int? = null
)

Solution

  • val albums by remember {
    mutableIntStateOf((artistStatsItem?.albums?.total as? Int) ?: 0)}
    

    I think the error can be fixed this way. I hope that will be useful