当前位置: 首页 > 知识库问答 >
问题:

科特林。TypeCastException:null 不能强制转换为非 null 类型 kotlin.collections.MutableList

糜博远
2023-03-14

请不要标记为重复,因为问题略有不同---

风景:-

我一直在使用改装执行删除购物车。。

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

2.if购物车是空的,它崩溃与上述错误

这是我的适配器代码:-

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--

2--

3--

对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

请帮帮我

共有3个答案

西门品
2023-03-14

使用购物车中要设置的零件中的Elvis运算符进行空检查

第一种或第二种方法似乎不错

颜志学
2023-03-14

找不到使用可变列表的原因,但您的问题是类型转换不正确(dataList 为可变列表)

邰棋
2023-03-14

看起来可以通过修改几行代码来解决:

让CartAdapter接受可空参数< code>dataList,因为您的api请求可能返回null,传递它会导致< code>NPE。

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

因为我们的<code>数据列表</code>是可空的,并且调用<code>dataList。size可能会抛出NPE。我们需要使用进行安全调用吗 。如果为空,我们只返回0,告诉<code>recyclerView</code>有0项。

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

需要制作<代码>价值追溯:列表

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

CartAdapter中删除init(),并在构造函数中的参数之前添加var(实际上应该是valinit()在这里是多余的,因为u或r使用它为冗余的重复成员变量赋值。通过在构造函数参数中添加var(应该是val),它们将被赋值,并在对象构造之后作为成员变量可用。

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

 (dataList?.isEmpty() ?: true)

或者使用

`(dataList.isNullOrEmpty())` 

哪个更干净,应该也管用。

注意:就个人而言,我不会建议您每次需要更改值时都重新定义适配器。相反,创建 val items = arrayListOf

 类似资料:
  • 我正在尝试初始化菜单上的自定义搜索工具(3d库),但我得到了错误。 但这无助于第136行对应于 菜单的xml

  • 我正在尝试在RecyclerView中添加搜索过滤功能。但应用程序因以下错误而崩溃: 科特林。TypeCastException:null不能转换为非null类型kotlin。收藏。请登录com。卡贝拉什。电影。用户界面。PostListAdapter$searchFilter$1。在android上发布结果(PostListAdapter.kt:87)。小装置。筛选$ResultsHandler

  • 问题内容: 让我们假设下表(例如,几个内部join语句的结果): 例如,您可以从以下语句中获取: 现在,如果我想将t1.column_1和t2.column_2总结如下 结果显示如下: 我的问题基本上是:有没有一种方法可以将NULL类型转换为0以便进行一些数学运算? 我曾尝试和,而是保持一个。 问题答案: 使用的列值转换到零。或者,COALESCE函数将执行相同的操作,除了(1)符合ANSI标准,

  • 从上面的标题来看,目前我遇到了一个问题,即无法从一个模型类转换到另一个模型类。我写的代码有问题吗?请随时向我询问更多信息。非常感谢。 我怀疑: 这种方法“selectTheOldFnException”有一些错误,那就是使用了hibernate,但我不确定这个理论。 REST控制器 使用HIBERNATE-MatchingEngine选择POJO。班 POJO班 例外代码

  • 我将调用(used)的响应传递给一个类,并尝试将其强制转换到我的模型类。由于我对调用使用的是registfit,因此它在使用GSON将其转换为模型类对象之前,根据服务器的响应生成一个链接的hashmap。(这就是我所理解的,如果我错了请纠正我)。我已经附加了一个使用response对象进行调试时可以看到的图像。如何将此响应转换为我的模型类或类型对象的对象。当我试图将类型对象强制转换到活动中的模型类

  • 应用程序属性 我也试图改变mysql的版本仍然一样。我该怎么解决这个?