0
votes

Do I have to use ?. and !!. every time inside onBindViewHolder and onCreateViewHolder ? Is there any way to avoid this?

holder.textview.text and parent.context showing this error.

Code :

override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
    holder.textview.text = items[position]
}

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int):ViewHolder {
    return ViewHolder(TextView(parent.context))
}
3

3 Answers

3
votes

When you're overriding a method declared in Java, its parameters will have platform types, which means there is no nullability information about them (unless they're explicitly annotated). It's up to you to decide whether or not to mark these parameters nullable. See the official docs about platform types.

In your case, you can safely remove the ? from both of these parameters, as they'll never be passed null values. This relieves you from having to do mandatory null checks.


Here's what it looks like with the nullable types removed:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.textview.text = items[position]
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    return ViewHolder(TextView(parent.context))
}
2
votes

When you work with nullable types as in your example, you have to apply safety measures to your code. Either you use ?. every time or you check if your parameter is !=null. After such an if the compiler knows that calls to this parameter are safe and null is not possible.

In your special case it’s not necessary to have nullable types though. Just remove the question marks from the parameters and everything is fine.

Btw: don’t use !!, there’s most certainly a better solution

1
votes

The viewholder will never be null unless if you created null viewholder in your onCreateViewHolder when the count > 0, so its safe to remove the ?

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.textview.text = items[position]
}