【问题标题】:Stuck with ArrayAdapter卡在 ArrayAdapter 上
【发布时间】:2020-06-04 03:01:04
【问题描述】:

我正在学习编写 Kotlin 代码作为一种爱好,但我碰壁了。我收到以下错误:

None of the following functions can be called with the arguments supplied: 
public constructor ArrayAdapter<T : Any!>(context: Context, resource: Int, objects: Array<(out) TypeVariable(T)!>) defined in android.widget.ArrayAdapter
public constructor ArrayAdapter<T : Any!>(context: Context, resource: Int, textViewResourceId: Int) defined in android.widget.ArrayAdapter
public constructor ArrayAdapter<T : Any!>(context: Context, resource: Int, objects: (Mutable)List<TypeVariable(T)!>) defined in android.widget.ArrayAdapter

在我从 openweather 添加 API 以提取一些数据之前,它工作正常。 任何帮助表示赞赏!

这是我的代码:

package com.example.myweatherapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ForecastActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_forecast)



         var retriever = WeatherRetriever()

            val callback = object : Callback<Weather> {
                override fun onFailure(call: Call<Weather>?, t: Throwable) {
                println("It failed")
                }

                override fun onResponse(
                    call: Call<Weather>?, response: Response<Weather>?) {
                    println("It wORKED")

                    println(response?.body()?.main)

                    title = response?.body()?.name

                    var forecasts = response?.body()?.main

                    var castListView = findViewById<ListView>(R.id.forecastListView)

                    var adapter = ArrayAdapter(this@ForecastActivity,android.R.layout.simple_list_item_1,forecasts)

                    castListView.adapter=adapter
                }

            }
            retriever.getForecast(callback)
        }

        }

【问题讨论】:

  • Response.Body.Main的类型是什么?它需要是一个数组或列表。此外,如果响应或正文为空,您将遇到问题。
  • 我正在尝试访问此 JSON 文件上的“主”数组,并将其内容作为结果:[链接]api.openweathermap.org/data/2.5/…

标签: android kotlin android-arrayadapter


【解决方案1】:
ArrayAdapter(this@ForecastActivity,android.R.layout.simple_list_item_1,forecasts)

ArrayAdapter 需要 Array/List of Object 作为第三个参数,但 forecasts 只是响应正文。

See more details here about ArrayAdapter constructors

您需要解析响应并准备一个对象列表/数组(即字符串标题)作为 ArrayAdapter 构造函数中的第三个参数传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 2023-03-03
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多