麻烦“For-Loop范围必须有'iterator()'方法”和JSON问题

时间:2018-01-22 10:04:53

标签: android json kotlin retrofit

我正在教自己Kotlin和android dev。所以,我确信我的大部分问题都是缺乏知识,但是我已经把这一部分挂了一两天。我认为我的问题部分是我的JSON查询,主要是我的新手。

在下面的for循环中,我从IDE中收到以下错误“For-Loop范围必须有'iterator()'方法”。这是关于:for(CycloneList中的stormInfo)中的'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)
    }
}

1 个答案:

答案 0 :(得分:0)

您的stormInfoList,提供强制性iterator(),这就是您要迭代的内容:

var cycloneList = response?.body()?.currenthurricane?.stormInfo ?: emptyList()

for (stormInfo in cycloneList) { }

希望它有所帮助...