我正在尝试从Kotlin的doAsyncResult获取ArrayList,并且一直在获取Future>我在Kotlin文档中了解了Future,但是我不明白我的代码使它返回的是Future而不是常规ArrayList。我正在使用Anko是为了清楚。
fun getMealById(mealId: String): ArrayList<String> {
var resultAL = doAsyncResult {
var jsonO =
JSONObject(URL("https://www.themealdb.com/api/json/v1/1/lookup.php?i=" + mealId).readText()).getJSONArray("meals").getJSONObject(0)
var mealInfoLocal = parseIndMeal(jsonO)!!
return@doAsyncResult mealInfoLocal
}
Log.i(TAG, "GetMealById has finished")
// if I print resultAL here, it comes out correct.
return resultAL
}
所有代码都可以正常工作,最终我得到想要的结果,它只是作为Future而不是常规变量返回。
parseIndMeal()函数:
private fun parseIndMeal(jsonO: JSONObject): ArrayList<String>? {
var mealInfo: ArrayList<String> = ArrayList(5)
//println("JsonO in parseIndMeal() - ")
if (jsonO.has("strMeal")) {
mealInfo.add(jsonO.getString("strMeal"))
} else {
println("JsonO is incomplete")
}
if (jsonO.has("strMealThumb")) {
mealInfo.add(jsonO.getString("strMealThumb"))
} else {
println("JsonO is incomplete")
}
if (jsonO.has("idMeal")) {
mealInfo.add(jsonO.getString("idMeal"))
} else {
println("JsonO is incomplete")
}
if (jsonO.has("strArea")) {
mealInfo.add(jsonO.getString("strArea"))
} else {
println("JsonO is incomplete")
}
if (jsonO.has("strInstructions")) {
mealInfo.add(jsonO.getString("strInstructions"))
} else {
println("JsonO is incomplete")
}
return mealInfo
}
谢谢!