0

我正在尝试从 Backendless 获取数据,我正在使用 kotlin 和 MVVM 架构。我对 Kotlin 和 MVVM 都很陌生。这些日期将显示在片段(位于选项卡中)的 recyclerView 中。我收到此错误:

 java.lang.IllegalArgumentException: Missing public, default no-argument constructor
    at com.backendless.Persistence.of(Persistence.java:833)
    at com.example.drake.kunuk.ui.buy.BuyViewModel.loadBuys(BuyViewModel.kt:26)
    at com.example.drake.kunuk.ui.buy.BuyViewModel.getBuys(BuyViewModel.kt:19)
    at com.example.drake.kunuk.ui.buy.BuyFragment.onActivityCreated(BuyFragment.kt:37)

..................................................... .....................

class BuyViewModel : ViewModel() {
// TODO: Implement the ViewModel
private lateinit var buys: MutableLiveData<List<Buy>>

fun getBuys(): LiveData<List<Buy>> {
    if(!::buys.isInitialized) {
        buys = MutableLiveData()
        loadBuys()
    }
    return buys
}

private fun loadBuys(){
    lateinit var buy: List<Buy>
    Backendless.Persistence.of(Buy::class.java)
        .find(object : AsyncCallback<List<Buy>> {
            /*This will give the response from Backendless*/
            override fun handleResponse(response: List<Buy>) {
                for (i in response.indices) {
                    buy = listOf(response[i])
                }
                buys.value = buy

            }
            override fun handleFault(fault: BackendlessFault?) {
                TODO("not implemented")
            }

        })

}
}

这是我的 BuyAdapter 的代码:

class BuyAdapter(internal var context: Context,
             internal var ressource: Int,
             internal var buyList: ArrayList<Buy>
) : RecyclerView.Adapter<BuyAdapter.ViewHolder>() {

override fun getItemCount(): Int {
    return buyList.size
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view = LayoutInflater.from(context)
        .inflate(ressource, parent, false)
    return ViewHolder(view)
}


override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val buy: Buy = buyList[position]

    holder.price.text = buy.price.toString()
}

class ViewHolder(v: View) : RecyclerView.ViewHolder(v){
    var price: TextView = v.tvPrice

}
4

1 回答 1

1

出现问题是因为数据类中没有任何无参数构造函数。所以我改变了这个:

data class Buy(val address: String,
           val price: Int,
           val propertyDesc: String,
           val numberOfRoom: Int,
           val numberOfBath: Int,
           val numberOfCar: Int,
           val propertyImage: String,
           val propertyLocation: String,
           val amenities: String)

对此:

data class Buy(var address: String = "",
           var price: Int = 0,
           var propertyDesc: String = "",
           var numberOfRoom: Int = 0,
           var numberOfBath: Int = 0,
           var numberOfCar: Int = 0,
           var propertyImage: String = "",
           var propertyLocation: String = "",
           var amenities: String = "")

要让编译器自动生成无参数构造函数,您必须为每个主要构造函数参数分配一个默认值,并记住 use var。或者您可以声明第二个不带参数的构造函数。

于 2018-12-28T08:21:20.160 回答