java.lang.ClassCastException:CustomAdapter无法强制转换为android.widget.ArrayAdapter在Kotlin中

时间:2018-05-16 05:16:02

标签: android kotlin android-adapter baseadapter listadapter

当我尝试在Kotlin

中创建自定义适配器类时,我遇到了上述错误

源代码

MainActivity.kt

 var adapterC:CustomAdapter = CustomAdapter(this,Statearray)
 spinnerState.adapter=adapterC

CustomAdapter.kt

class CustomAdapter(val activity: Activity,val array:JSONArray) : BaseAdapter(), ListAdapter
{
    lateinit var ItemName: TextView

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
    var view=convertView
    if (view == null)
        view = activity.layoutInflater.inflate(R.layout.spinnerlayout, null)
    try {

        ItemName = view?.findViewById(R.id.ItemName) as TextView
        val obj = array.getJSONObject(position)
        ItemName.setText(obj.getString("Name"))
        view.setTag(obj.getString("Id"))

    } catch ( e:JSONException) {
        Log.e("At Custom Class",e.toString())
    }

    return view
}

override fun getItem(position: Int): JSONObject {
    return array.optJSONObject(position)
}

override fun getItemId(position: Int): Long {
    var jsonObject=getItem(position)
    return jsonObject.optLong("id")
}

override fun getCount(): Int {
    return array.length()
}

}

需要帮助我不知道我做错了什么。

2 个答案:

答案 0 :(得分:1)

ClassCastException

  

抛出以指示代码已尝试将对象强制转换为   它不是实例的子类。

<强> FYI

您添加了 Multiple Adapter 。删除第二个。

<强>

class CustomAdapter(val activity: Activity,val array:JSONArray) : BaseAdapter(), ListAdapter

<强>不要

class CustomAdapter(context: Context,var arrayLIST: ArrayList<Response>) : BaseAdapter() {

<强>样本

var arrayLIST: ArrayList<Response>? = null

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

        arrayLIST=ArrayList()
        val jsonObj = ("[{\"Id\":\"35\",\"Name\":\"Kerala\"},{\"Id\":\"36\",\"Name\":\"Tamilnadu\"}]")
        val jo = JSONArray(jsonObj)
        val num = 0 until jo.length()
        for (i in num) {
            val loanObj = jo.getJSONObject(i)
            val Id      = loanObj.getString("Id")
            val Name    = loanObj.getString("Name")

            arrayLIST!!.add(Response(Id,Name))


        }
      var adapterC:CustomAdapter = CustomAdapter(this@MainActivity,arrayLIST)

<强> Response.kt

data class Response
(
        @SerializedName("id")               val id               : String,
        @SerializedName("name")            val  name             : String
)

注意

确保添加,

   implementation "com.google.code.gson:gson:2.3.0"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"

答案 1 :(得分:1)

我终于明白了..问题是,我使用的是只支持ArrayAdapter的微调器库

我使用的库是

netcore

它只支持arrayadapter