kotlin.TypeCastException:null 无法转换为非 null 类型 kotlin.collections.MutableList

2024-02-29

请不要标记为重复,因为问题略有不同 ---> null 不能转换为非 null 类型 kotlin.collections。可变列表

应用场景:-

我一直在使用改造执行删除购物车..

  1. 如果至少存在一项,它将显示在 recyclerview 中

2.如果购物车是空的,则会崩溃并出现上述错误

这是我的适配器代码:-

class CartAdapter(context: Context, dataList: MutableList<DataCart?>) :
RecyclerSwipeAdapter<CartAdapter.CustomViewHolder>() { //added RecyclerSwipeAdapter and override
 private   var dataList: MutableList<DataCart>
private val context: Context
 lateinit var  dialog:ProgressDialog
var progressDialog: ProgressDialog? = null


inner class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val mView: View
   val swipelayout:SwipeLayout
    val productiamge: ImageView
    val productname: TextView
    val productcategory: TextView
    val productprice: TextView
    val quantity:TextView
    val tvDelete:TextView
    init {
        mView = itemView
    productiamge= mView.findViewById(R.id.imagecart)
       productname= mView.findViewById(R.id.imagenamecart)
        productcategory= mView.findViewById(R.id.imagecategory)
     productprice =mView.findViewById(R.id.price)
        quantity=mView.findViewById(R.id.quantity)
        swipelayout=mView.findViewById(R.id.swipe)
        tvDelete=mView.findViewById(R.id.tvDelete)
    }

}

      override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
    val layoutInflater = LayoutInflater.from(parent.context)
    val view: View = layoutInflater.inflate(R.layout.addtocart_item, parent, false)
    return CustomViewHolder(view)
}

override fun getSwipeLayoutResourceId(position: Int): Int {
    return R.id.swipe;

}

override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
  val  progressDialog :ProgressDialog= ProgressDialog(context);

    holder.productname.text = dataList.get(position).product.name ?: null
    holder.productcategory.text = "(" +dataList.get(position).product.product_category +")"

    holder.productprice.text = dataList.get(position).product.cost.toString()

    Glide.with(context).load(dataList.get(position).product.product_images)
        .into(holder.productiamge)
    holder.quantity.text=dataList.get(position).quantity.toString()

    holder.swipelayout.setShowMode(SwipeLayout.ShowMode.PullOut)
    Log.e("checkidd",dataList.get(position).product.id.toString())
    // Drag From Right

    // Drag From Right
    holder.swipelayout.addDrag(
        SwipeLayout.DragEdge.Right,
        holder.swipelayout.findViewById(R.id.bottom_wrapper)
    )
    val id =dataList.get(position).product?.id

        holder.swipelayout.addSwipeListener(object : SwipeListener {
        override fun onClose(layout: SwipeLayout) {            }

        override fun onUpdate(layout: SwipeLayout, leftOffset: Int, topOffset: Int) {
            //you are swiping.
        }

        override fun onStartOpen(layout: SwipeLayout) {}
        override fun onOpen(layout: SwipeLayout) {
        }

        override fun onStartClose(layout: SwipeLayout) {}
        override fun onHandRelease(
            layout: SwipeLayout,
            xvel: Float,
            yvel: Float
        ) {
        }
    })
    holder.swipelayout.getSurfaceView()
        .setOnClickListener(View.OnClickListener {
        })

   holder.tvDelete.setOnClickListener(View.OnClickListener {
    view ->

    val token :String = SharedPrefManager.getInstance(context).user.access_token.toString()
RetrofitClient.instancecart.deletecart(token,id!!)
    .enqueue(object : Callback<DeleteResponse> {
        override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
        }

        override fun onResponse(
            call: Call<DeleteResponse>,
            response: Response<DeleteResponse>
        ) {
            var res = response

            if (res.body()?.status==200) {
                Toast.makeText(
                    context,
                    res.body()?.message,
                    Toast.LENGTH_LONG
                ).show()
                progress()
                mItemManger.removeShownLayouts(holder.swipelayout)
                notifyItemChanged(position)
                notifyItemRemoved(position)
                dataList?.removeAt(position)
                notifyItemRangeChanged(position, dataList?.size!!)
                mItemManger.closeAllItems()
                progressDialog.show()
            }
            else{
                try {
                    val jObjError =
                        JSONObject(response.errorBody()!!.string())
                    Toast.makeText(
                        context,
                        jObjError.getString("message")+jObjError.getString("user_msg"),
                        Toast.LENGTH_LONG
                    ).show()
                } catch (e: Exception) {
                    Toast.makeText(context, e.message, Toast.LENGTH_LONG).show()
                    Log.e("errorrr",e.message)
                }
            }
        }
    })
mItemManger.bindView(holder.itemView, position)
     })
}
override fun getItemCount(): Int {
    return dataList.size
}
fun progress()
{
    progressDialog?.dismiss()
    val intent =
        Intent(context.applicationContext, AddToCart::class.java)
    intent.flags =
        Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
    context.applicationContext.startActivity(intent)
}

    init {
    this.context = context
    this.dataList = dataList 
   }}

这是我的活动:

   class AddToCart:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.add_to_cart)
   val totalamount:TextView=findViewById(R.id.totalamount)
    val token: String =
        SharedPrefManager.getInstance(
            applicationContext
        ).user.access_token.toString()
    RetrofitClient.instancecart.listcart(token).enqueue( object :
        Callback<CartResponse> {
        override fun onFailure(call: Call<CartResponse>, t: Throwable) {
            Toast.makeText(applicationContext,"falied", Toast.LENGTH_LONG).show()
        }

        override fun onResponse(
            call: Call<CartResponse>,
            response: Response<CartResponse>
        ) {
            val res=response
            if (response.isSuccessful) {
                val retro:List<DataCart> = response.body()!!.data
      totalamount.setText(response.body()?.total.toString())

                generateDataList(retro as MutableList<DataCart?>)

            }
        }

    })
}
fun generateDataList( dataList:MutableList<DataCart?>) {
    val recyclerView=findViewById<RecyclerView>(R.id.addtocartrecyleview) as? RecyclerView
    val linear:LinearLayoutManager=
        LinearLayoutManager(applicationContext,LinearLayoutManager.VERTICAL, false)
    recyclerView?.layoutManager=linear
    val adapter = CartAdapter(this@AddToCart,dataList)
    recyclerView?.adapter=adapter
    recyclerView?.addItemDecoration
    (DividerItemDecorator(resources.getDrawable(R.drawable.divider)))
    recyclerView?.setHasFixedSize(true)

    adapter.notifyDataSetChanged()

    if (dataList.isEmpty()) {
        recyclerView?.setVisibility(View.GONE)
        textviewempty.setVisibility(View.VISIBLE)
    } else {
        recyclerView?.setVisibility(View.VISIBLE)
        textviewempty.setVisibility(View.GONE)
    }




  recyclerView?.addOnScrollListener(object :
        RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            Log.e("RecyclerView", "onScrollStateChanged")
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
        }
    })
}

override fun onBackPressed() {
    super.onBackPressed()
    val intent = Intent(this, HomeActivity::class.java)
    startActivityForResult(intent, 2)
}

}

我尝试过这个-->通过做一些改变-->

1--> var dataList: MutableList

2--> var dataList: MutableList?=null

3--> var dataList: 可变列表

对 Arraylist 执行 Mutablelist 后的错误日志

kotlin.TypeCastException: null cannot be cast to non-null type java.util.ArrayList<com.example.store.Cart.DataCart>
    at com.example.store.Cart.AddToCart$onCreate$1.onResponse(AddToCart.kt:40)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7147)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)

但似乎没有任何东西可以处理 null

请帮我


看起来可以通过更改几行来修复它:

使 CartAdapter 接受可为 null 的参数dataList,因为你的 api 请求可能返回 null 并且传递它会导致NPE.

class CartAdapter(context: Context, dataList: MutableList<DataCart?>?)

自从我们的dataList可为空并调用dataList.size可能会抛出NPE我们需要使用以下方式进行安全调用?。如果它为空,我们只返回 0,告诉recyclerView有 0 件商品。

override fun getItemCount() = datalist?.size ?: 0

需要制作val retro:List<DataCart>可以为空,因为response.body()?.data可能会回来null。我们只是转换retro使用扩展函数到 mutableListtoMutableList(),带有安全呼叫操作员"?". If retro is null then null值将被传递到CartAdapter,并且由于我们的适配器处理null值它将继续而不会出现错误

if (response.isSuccessful) {
                val retro:List<DataCart>? = response.body()?.data
                totalamount.setText(response.body()?.total.toString())
                generateDataList(retro?.toMutableList())
            }

Remove init()函数来自CartAdapter并添加var(实际上应该是val) 在构造函数中的参数之前。init()这里是多余的,因为你用它来给多余的、重复的成员变量赋值。通过添加 var( 应该是val)到构造函数参数,它们将在对象构造之后立即被赋值并可用作成员变量。


Since dataList可以为空,我们需要确定它的大小以便需要使用进一步的逻辑安全调用,并且如果它null return true- 空的

 (dataList?.isEmpty() ?: true)

or use

`(dataList.isNullOrEmpty())` 

这更干净,也应该有效。


NOTE:就个人而言,我不建议您每次需要更改值时都初始化适配器。而是创建 valitems = arrayListOf<DataCart>().作为成员变量并添加一个用于更新它的 setter 函数,您可以在其中调用notifyDatasetChanged()或其他通知方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

kotlin.TypeCastException:null 无法转换为非 null 类型 kotlin.collections.MutableList 的相关文章

随机推荐