How to pass a string-array from the function to the activity in android kotlin?

Issue

I am trying to pass a string-array from function to activity. I want to use that array into the spinner. But when I am trying to do this, I am passing an array but the function wants to pass a array of type Int. But in activity array of Array<String> type is required.

here is the code of the activity:-

fun selectingDistrictLocation() {
    val (districtArray: Int, districtVisibility: Int, stateWarningVisibility: Int, recyclerViewVisibility: Int) = selectedState(SelectedStateName)
    district_location.visibility = districtVisibility
    state_warning.visibility = stateWarningVisibility
    val locationDistrictAdapter = ArrayAdapter(
        this,
        R.layout.support_simple_spinner_dropdown_item,
        districtArray
    )
    districts_spinner_location.adapter = locationDistrictAdapter

    districts_spinner_location.onItemSelectedListener =
        object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                adapterViewDistrict: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                DistrictSelectedName =
                    adapterViewDistrict?.getItemAtPosition(position).toString()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }
}

here is function code:-

object RegionSelectionFunctions {

    fun selectedStateForSmallRegions(state: String): SelectingDistrictLocationArrayForSmallRegions {
        when (state) {
            "-- Select State --" -> return SelectingDistrictLocationArrayForSmallRegions(R.array.empty,View.GONE, View.VISIBLE, View.GONE)
        }
    }

here is the code of the data class:-

data class SelectingDistrictLocationArray(
    val DistrictList: Array<String>,
    val districtVisibility: Int,
    val stateWarningVisibility: Int,
    val recyclerViewVisibility: Int) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as SelectingDistrictLocationArray
        if (!DistrictList.contentEquals(other.DistrictList)) return false

        return true
    }

    override fun hashCode(): Int {
        return DistrictList.contentHashCode()
    }
}
            

I have tried all the possible ways I know to solve this. Can someone please help me?

Solution

It is not possible to convert java.lang.Integer cannot be cast to java.lang.String[].

Refer to this question.

For doing the same thing you can pass the string as a value for each case. Then compare that case in the activity. Assign the values of the arrays in the activity.

Answered By – Prasad v Bhagat

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *