gpt4 book ai didi

android - 如何在 Kotlin Android 中从 JSON 中获取数据

转载 作者:行者123 更新时间:2023-11-29 18:46:01 28 4
gpt4 key购买 nike

我想获取一些json数据,见图中绿色箭头:

enter image description here

问题是 Android Studio 不允许我获取我想要的数据。它停止直到前一步(我认为)。在我的适配器类检查中:

holder?.view?.textWeather?.text = weatherFor.weather.toString()

还在模拟器中显示红色箭头,这是什么?

下面是我的主要 Activity 的 json 方法,其中包含我要为其获取数据的类,以及关联的 Adapter 类。

主要 Activity

fun fetchJson() {
val url="https://api.openweathermap.org/data/2.5/forecast?q=Prague,CZ&appid=4cf7f6610d941a1ca7583f50e7e41ba3"
val request=Request.Builder().url(url).build()
val client= OkHttpClient()
client.newCall(request).enqueue(object :Callback {

override fun onResponse(call: Call?, response: Response?) {
val body=response?.body()?.string()
println(body)

val gson=GsonBuilder().create()

val forecastfeed=gson.fromJson(body,ForecastFeed::class.java)

runOnUiThread{
recyclerView_main.adapter=MainAdapter(forecastfeed)
}
}

override fun onFailure(call: Call?, e: IOException?) {
println("Failed to execute request")
}
})
}

class ForecastFeed(val list:List<ForecastWeatherList>) { }

class ForecastWeatherList(val weather:List<WeatherData>) { }

class WeatherData(val main:String,val icon:String) { }

适配器

class MainAdapter(val forecastfeed: ForecastFeed): RecyclerView.Adapter<CustomViewHolder>() {

val forecastWeather = listOf<String>("First","Second")

override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
val weatherFor = forecastfeed.list.get(position)
holder?.view?.textWeather?.text = weatherFor.weather.toString()
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder{
//how do we even create a view
val layoutInflater =LayoutInflater.from(parent?.context)
val cellForRow=layoutInflater.inflate(R.layout.weather_row,parent,false)
return CustomViewHolder(cellForRow)
}

override fun getItemCount(): Int {
return forecastfeed.list.count()
}
}

class CustomViewHolder(val view: View):RecyclerView.ViewHolder(view) { }

最佳答案

您可以手动格式化数据

holder?.view?.textWeather?.text = "weather ${weatherFor.weather.map{it.main}.joinToString(", ")}"

或使用 data classes

关于android - 如何在 Kotlin Android 中从 JSON 中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51930167/

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