A
A
Alina Mitrokhina2020-02-12 01:21:52
Android
Alina Mitrokhina, 2020-02-12 01:21:52

Why is a ClassCastException thrown in onBindViewHolder?

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is FirstLetterViewHolder -> {
                val firstLetter = dataSource[position] as FirstLetter
                holder.bind(firstLetter.letter.toString())
            }
            is AcronymViewHolder -> {
                val acronym = dataSource[position] as Acronym
                holder.bind(acronym)
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2020-02-16
@fursa08

Obviously, the logic of working with data is incorrectly described in the adapter class.
There should be synchronism between the model (that you have the `dataSource` field) and the ViewHolder.
Practically, this means that in the method (based on the fact that RecyclerView is used)
`getItemViewType` must return a unique int-id for each model class. for example

override fun getItemViewType(position: Int): Int {
        return when (val item = dataSource[position]) {
            is FirstLetter -> 1
            is Acronym ->2
            else -> throw IllegalArgumentException("unknown item type $item")
        }
    }

and in `onCreateViewHolder` a ViewHolder should be returned that corresponds to a unique identifier for the position (for example, `FirstLetterViewHolder` should be created for `viewType == 1`)
Thus, the synchronism of ViewHolders and the model will be organized.
That is, if `AcronymViewHolder` is passed to the onBindViewHolder method, then `Acronym` will always be in dataSource[position]

A
AndroidDev2015, 2020-02-12
@AndroidDev2015

Before ghosting a type, you need to check that this is possible.
Try "instanceof" operator in java "if(x instanceof Integer)" or "is" in kotlin "if(x is Integer)"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question