Jetpack compose Invalid ID 0x00000000



我正在制作一个非常简单的应用程序,我在地图上用不同的图标点,一个天气图。问题是,我使用的函数持续一段时间来提取另一个线程中的信息。因此,程序继续运行,当我使用它时,值不会更新。

这是天气API的代码。

private val appid = "??"
private var icon: String = ""
fun tiempo_ciudad(id: String, context: Context, callback: (String) -> Unit) {
val tempUrl = "https://api.openweathermap.org/data/2.5/weather?id=" + id + "&appid=" + appid
val stringRequest = StringRequest(
Request.Method.POST,
tempUrl,
{ response ->
val json = JSONObject(response)
val weather = json.getJSONArray("weather").getJSONObject(0)
icon = "_"+weather.getString("icon")
callback(icon)
},
{ error ->
// maneja el error
}
)
val requestQueue = Volley.newRequestQueue(context)
requestQueue.add(stringRequest)
}

fun getIcon(id: String, context: Context, callback: (String) -> Unit) {
tiempo_ciudad(id, context) {
icon -> callback(icon)
}
}

这是我用来生成点的代码,有没有办法等到getIcon工作?

@Composable
fun generapunto(context: Context, id: String, x: Int, y:Int) {
var icon = ""
getIcon(id, context) { retrievedIcon ->
icon = retrievedIcon
}
val resourceId = context.resources.getIdentifier(icon, "mipmap", context.packageName)
Box( modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(top = y.dp, start = x.dp)) {
Image(
painter = painterResource(resourceId),
contentDescription = null,
modifier = Modifier
.size(50.dp)
.clip(CircleShape)
.background(Color(red = 222f / 255f, green = 225f / 255f, blue = 250f / 255f))
)
}
}

示例:

@Composable
fun generapunto(context: Context, id: String, x: Int, y:Int) {
var icon by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
getIcon(id, context) { retrievedIcon ->
icon = retrievedIcon
}
}
if(icon.isNotBlank()) {
val resourceId = context.resources.getIdentifier(icon, "mipmap", context.packageName)
Box( modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(top = y.dp, start = x.dp)) {
Image(
painter = painterResource(resourceId),
contentDescription = null,
modifier = Modifier
.size(50.dp)
.clip(CircleShape)
.background(Color(red = 222f / 255f, green = 225f / 255f, blue = 250f / 255f))
)
}
}
}

相关内容

  • 没有找到相关文章

最新更新