gpt4 book ai didi

java - 在 uiThread 中获取 Fuel 结果

转载 作者:行者123 更新时间:2023-11-30 05:00:13 25 4
gpt4 key购买 nike

我使用名为“Fuel”的库从服务器获取数据,这是我的代码:

button1.setOnClickListener {
val jb = "{......}"

Fuel.post("server_url")
.header(Headers.CONTENT_TYPE, "application/json")
.body(jb)
.response { request, response, result ->
Log.d("test", request.toString())
Log.d("test", response.toString())
val (bytes, error) = result
if (bytes != null) {
val e = JsonParser().parse(String(bytes))
val obj = e.asJsonObject
val rm = obj.get("rm").asString
}
}
}

但问题来了:我怎样才能得到“rm”的值?

它是在 Fuel 函数中定义的,我无法从 Fuel 外部获取它的值...

谁能帮我看看如何得到它?

最佳答案

可以在响应对象外声明一个var并设置值

var globalRM : String? = null;
button1.setOnClickListener {
val jb = "{......}"
var rm : String? = null;
Fuel.post("server_url")
.header(Headers.CONTENT_TYPE, "application/json")
.body(jb)
.response { request, response, result ->
Log.d("test", request.toString())
Log.d("test", response.toString())
val (bytes, error) = result
if (bytes != null) {
val e = JsonParser().parse(String(bytes))
val obj = e.asJsonObject
globalRM = obj.get("rm").asString
rm = obj.get("rm").asString
}
}
}

您可能还想在获取值后立即执行一些操作,在这种情况下,创建一个方法并使用它:

onCreate(...){
button1.setOnClickListener {
val jb = "{......}"
var rm : String? = null;
Fuel.post("server_url")
.header(Headers.CONTENT_TYPE, "application/json")
.body(jb)
.response { request, response, result ->
Log.d("test", request.toString())
Log.d("test", response.toString())
val (bytes, error) = result
if (bytes != null) {
val e = JsonParser().parse(String(bytes))
val obj = e.asJsonObject
globalRM = obj.get("rm").asString
rm = obj.get("rm").asString
onFuelFetched(rm)
}
}
}
}

fun onFuelFetched(val rm:String?){
// do anything you wish to do with this value here
}

关于java - 在 uiThread 中获取 Fuel 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com