Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView

后端 未结 4 695
刺人心
刺人心 2021-01-03 21:54

I got this error just after converted the adapter code to Kotlin:

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.         


        
相关标签:
4条回答
  • 2021-01-03 22:27

    The getView() method is a part of the Adapter interface, and is defined in Java. Documentation here. The important part is this note about the convertView parameter:

    View: The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using.

    This means that it's quite valid for the framework to pass null values for convertView to this method (meaning that you need to create a new view and return that, rather than recycling an old view).

    In turn, this means that the Kotlin definition of convertView must be of type View?, not just View. So change your function signature to this:

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View
    
    0 讨论(0)
  • 2021-01-03 22:31

    All correct solutions are already posted above. Just one more with some code and ViewBinding:

    class SpinnerAdapter(
          context: Context,
          private val items: List<YourModel>
    ) : BaseAdapter() {
    
    private var layoutInflater: LayoutInflater = LayoutInflater.from(context)
    
    override fun getView(i: Int, convertView: View?, viewGroup: ViewGroup): View {
        return if (convertView != null) {
            convertView
        } else {
            val view = layoutInflater.inflate(R.layout.item_spinner, null)
            val binding = ItemSpinnerBinding.bind(view)
            val item = items[i]
            binding.name.text = item.name
            view
        }
    }
    
    //more overridde methods
    }
    

    Where my R.layout.item_spinner has a TextView with an Id called "name".

    0 讨论(0)
  • 2021-01-03 22:42

    Change your convertView in getView from non-null to nullable

    override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
    

    to

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
    
    0 讨论(0)
  • 2021-01-03 22:50

    Make convertView nullable:

    convertView: View?
    

    I'm not sure why the line number is wrong, but the stacktrace tells you where to look in the error message.

    0 讨论(0)
提交回复
热议问题