android Jetpack组合无效ID 0x0000000

mwkjh3gx  于 2023-01-07  发布在  Android
关注(0)|答案(1)|浏览(215)

我正在做一个非常简单的应用程序,我用不同的图标在一张Map上画点,一张天气图。问题是我使用的函数需要一段时间才能在另一个线程中提取信息。所以程序一直在运行,当我使用它时,值不会更新。
这是天气的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))
        )
    }
}
w6mmgewl

w6mmgewl1#

示例

@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))
            )
        }
    }
}

相关问题