Andrain
Andrain

Reputation: 910

How to solve kotlin type cast exception: null cannot be cast as null kotlin.collections.ArrayList

I am new to Kotlin and unable to solve this exception, I have tried different solutions from the net. I am fetching list of data from api and want to assign it to the spinner through databinding, but my code is crashing when I am assigning it to mutable arraylist in the success block of the api call.

this is my list declaration

private val _operators: MutableLiveData<ArrayList<Networks>>? = NotNullMutableLiveData(arrayListOf())
val operators: MutableLiveData<ArrayList<Networks>>? get() = _operators

Api call

fun getShops() {
    addToDisposable(api.getShoppingList().with()
        .doOnSubscribe {}
        .doOnSuccess {}
        .doOnError {}
        .subscribe({ result ->
             // getting crash here 
             _operators?.value = result.Data.get(0).items as ArrayList<Networks>
           
        }, { error ->
        })
    )
  }

Upvotes: 0

Views: 331

Answers (1)

chand mohd
chand mohd

Reputation: 2550

Your MobileNetworks list is null to avoid NPE add ? operator to check Nullability

 _operators?.value = result.PaymentMethods.get(0).mobileNetworks as 
                 ArrayList<MobileNetworks>? 

Upvotes: 1

Related Questions