Search code examples
androidandroid-studiokotlinandroid-arrayadapter

How to fix type mismatch in ArrayAdapter?


I don't know how to fix this error of arrayadapter parameter, it shows me this error :

Type mismatch. Required:(Mutable)List<TypeVariable(T)!> Found: ArrayList<String!>?

It's only happening when I transfer the ArrayList of strings from the main activity to another.

class playerList2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_player_list3)
    var intent = intent
    var liste = intent.getStringArrayListExtra("players")
    val adapt = ArrayAdapter(this,android.R.layout.simple_list_item_1,liste)
    listView.adapter = adapt
    }
}

Solution

  • I think it's cause "liste" could be null, take a look at the final "?" of ArrayList<String!>? The adapter expects a non nullable list, you can check first if the ArrayList is not null and then use it or, the easy way if you are sure the array will always bring information use this:

    val adapt = ArrayAdapter(this, android.R.layout.simple_list_item_1, liste!!)
    

    The secure way would be:

    liste?.let{
      val adapt = ArrayAdapter(this, android.R.layout.simple_list_item_1, it)
    }
    

    Or, as @cactustictacs indicate, this would be the most correct way:

    val adapt = ArrayAdapter(this, android.R.layout.simple_list_item_1, liste ?: emptyList())
    

    I recomend to use the secure way always!