Adam Lee
Adam Lee

Reputation: 576

Kotlin: Convert a map's key set into a String Array

I am trying to set the options of a Spinner's drop-down menu, which requires taking in an Array of options as the last parameter. However, when I run my code, I get the following error:

java.util.HashMap$KeySet cannot be cast to java.lang.String[]

Below is my code:

var ringtoneNamesToURIs: MutableMap<String, String> = getRingtoneList()
var ringtoneNames: Array<String> = ringtoneNamesToURIs.keys as Array<String>

val ringtoneSpinner = root.findViewById(R.id.ringtoneSpinner) as Spinner
val ringtoneDropdown: ArrayAdapter<String>? = context?.let {
    ArrayAdapter<String>(
        it,
        android.R.layout.simple_spinner_item,
        ringtoneNames
    )
}

Upvotes: 1

Views: 2670

Answers (1)

David Rauca
David Rauca

Reputation: 1583

The keys in a map are saved in a Set, not in an array. So you can not just cast. You have to covert the keys set to an array.

val ringtoneNames:Array<String> = ringtoneNamesToURIs.keys.toTypedArray() 

Upvotes: 1

Related Questions