【发布时间】:2018-01-22 10:04:53
【问题描述】:
我正在自学 Kotlin 和 android dev。所以,我确信我的大部分问题是缺乏知识,但我已经被这部分挂断了一两天。我认为我的问题部分是我的 JSON 查询,主要是我的菜鸟。
在下面的 for 循环中,我从 IDE 中收到以下错误“For-Loop 范围必须具有 'iterator()' 方法”。这是关于 'cycloneList' 的:for(stormInfo in cycloneList)
我已经链接了我正在使用的“虚拟”JSON 数据,可以在此处找到:https://api.myjson.com/bins/19uurt 以在问题中节省一点空间。
问题代码
`var cycloneList = response?.body()?.currenthurricane?.stormInfo?.get(0)
if (cycloneList != null) {
for (stormInfo in cycloneList) { <<--Problem
val newCyclone = "Name: ${cycloneList.stormName}"
cycloneStrings.add(newCyclone)
}
}`
完整代码
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//creates a new CycloneRetriever object from CycloneHelp.kt
var retriever = CycloneRetriever()
val callback = object : Callback<Cyclones> {
override fun onResponse(call: Call<Cyclones>?, response: Response<Cyclones>?) {
println("Got a response!")
var cycloneList = response?.body()?.currenthurricane?.stormInfo?.get(0)
var cycloneStrings = mutableListOf<String>()
if (cycloneList != null) {
for (stormInfo in cycloneList) { //TODO Figure this out!!
val newCyclone = "Name: ${cycloneList.stormName}"
cycloneStrings.add(newCyclone)
}
}
var layoutMovieListView = movieListView
var movieListAdapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_list_item_1,
cycloneStrings)
layoutMovieListView.adapter = movieListAdapter
}
override fun onFailure(call: Call<Cyclones>?, t: Throwable?) {
println("The thing, it failed!")
}
}
retriever.getCyclones(callback)
}
我正在使用 Retrofit 访问/处理 JSON 数据
改造 JSON 代码
interface WeatherWunderGroundAPI {
@GET("bins/19uurt")
fun getCyclones() : Call<Cyclones>
}
class Cyclones(val currenthurricane: CurrentHurricane)
class CurrentHurricane(val stormInfo: List<StormInfo>)
class StormInfo(val stormName: String)
class CycloneRetriever {
val service : WeatherWunderGroundAPI
init {
val = retrofitCyclone
Retrofit.Builder().baseUrl("https://api.myjson.com/")
.addConverterFactory(GsonConverterFactory.create()).build()
service = retrofitCyclone.create(WeatherWunderGroundAPI::class.java)
}
fun getCyclones(callback: Callback<Cyclones>) {
val call = service.getCyclones()
call.enqueue(callback)
}
}
【问题讨论】:
标签: android json kotlin retrofit