返回自定义数组列表并将其分片

时间:2018-06-23 10:04:55

标签: android kotlin

我为所有API调用创建了一个类,当我在该类中调用方法时,它将返回一个自定义ArrayList。从返回的列表中,我只想提取车辆名称 ApiCalls.kt

class ApiCalls {
val client = OkHttpClient()
val list: ArrayList<VehicleListModel>? = null
public fun getEnquiryList(id:String): ArrayList<EnquiryModel>? {
    return null
}
public fun getVehicleList(): ArrayList<VehicleListModel> {

    val body = FormBody.Builder()
            .build()
    val request = Request.Builder()
            .post(body)
            .url(URLs.URL_GET_VEHICLE_LIST)
            .build()
    val callGetVehicleList = client.newCall(request)
    callGetVehicleList?.enqueue(object : Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            if (call == null || call.isCanceled)
                return
            }

        override fun onResponse(call: Call?, response: Response?) {
            if (call == null || call.isCanceled)
                return
            val resp = response?.body()?.string()

            try {


                val jo = JSONObject(resp)
                val message = jo.getJSONArray("VehicleModelList")

                for (i in 0 until message.length()) {
                    val json = message.getJSONObject(i)
                    val vehicleListId = json.getString("_id")
                    val vehicleListName =json.getString("vehicle_model_name")
                    val vehicle = VehicleListModel(vehicleListId, vehicleListName)
                    if (list != null) {
                        list.add(vehicle)
                    }
                   Log.e("....................",vehicleListId)
                }

            } catch (e: Exception) {

            }
        }
    })

    return list!!
}

}

从我的片段中调用该类

list= ApiCalls().getVehicleList()
    for (i in 0 until list.size)
    {
        labels.add(list[i].vehicleName)
    }
    val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item,labels)
   adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

  vehiclelist.adapter = adapter

我收到此错误

FATAL EXCEPTION: main
Process: abc.com.app, PID: 23077
kotlin.KotlinNullPointerException

希望我已经解决了问题

2 个答案:

答案 0 :(得分:0)

您必须将所有代码包含在ApiCalls中:

class ApiCalls {
 companion object {
    //code
 }
}

这等效于Kotlin中的static,因为您没有实例化ApiCalls类型的对象。 同样,您在致电时也不需要括号:

list= ApiCalls.getVehicleList()

答案 1 :(得分:0)

问题是这样的:

if (list != null) {
    list.add(vehicle)
}

listnull开头,从不调用list.add

您必须首先初始化list,然后上述if语句才能按预期工作。

因此,在上述if语句之前,在某处执行list = ArrayList<VehicleListModel>()

我指的是list类中的ApiCalls