please dont marked as duplicate , as the question is slightly different ---> null cannot be cast to non-null type kotlin.collections.MutableList
Looks like it can be fixed by changing few lines:
Make CartAdapter accept nullable argument dataList
, since your api request may return null and passing it would cause NPE
.
class CartAdapter(context: Context, dataList: MutableList?)
Since our dataList
is nullable and calling dataList.size
might throw NPE
we need to make safe call using ?
. And if it's null we just return 0, telling recyclerView
that there are 0 items.
override fun getItemCount() = datalist?.size ?: 0
Need to make val retro:List
nullable, because response.body()?.data
may return null
. We just convert retro
to mutableList using extension function toMutableList()
, with safe call operator "?"
. If retro
is null
then null
value will be passed to CartAdapter
, and since our adapter handles null
value it will proceed without errors
if (response.isSuccessful) {
val retro:List? = response.body()?.data
totalamount.setText(response.body()?.total.toString())
generateDataList(retro?.toMutableList())
}
Remove init()
function from CartAdapter
and add var
(actually should be val
) before arguments in constructor. init()
is redundant here because u r using it to assign values to redundant, duplicate member variables. By adding var(should be val
) to constructor arguments they will be assigned values and be available as member variables, right after object construction.
Since dataList
is nullable, and we need to determine its size for further logic safe call needs to be used, and if its null
return true
- empty
(dataList?.isEmpty() ?: true)
or use
`(dataList.isNullOrEmpty())`
which is cleaner, and should work too.
NOTE: Personally, i would'nt suggest you to retinitialize Adapter everytime you need to change values. Instead create val items = arrayListOf
as a member variable and add a setter function for updating it, inside of which you would call notifyDatasetChanged()
or other notify methods.