Adifyr
Adifyr

Reputation: 2679

Convert EditText Array to String Array - Kotlin Android

I have an array of EditTexts that I would like to get converted into an Array of Strings containing the input values of each of the EditTexts. Here is my code:

val textFields = arrayOf<EditText>(dialogView.findViewById(R.id.et_name),
            dialogView.findViewById(R.id.et_address), dialogView.findViewById(R.id.et_phoneNo),
            dialogView.findViewById(R.id.et_amount), dialogView.findViewById(R.id.et_remark))

How do I get a String Array of the values of the EditTexts with minimal code?

Edit: Basically I want to fit the code as an argument in a function. I would prefer to have it done without using a for-loop. Perhaps an inline function that would give out an array transforming (as given in the function block) each element (EditText) of the original one to a string. I couldn't find any method so far (although it might turn out to be something obvious).

I also need to use it as a vararg parameter.

Upvotes: 0

Views: 1069

Answers (1)

Anthony Cannon
Anthony Cannon

Reputation: 1273

Todo this you have to map it into a string array by doing the following:

val newTextFieldStringArray = textFields.map { it.text.toString() }
Log.e("TEST", newTextFieldStringArray.toString()) // print it out

Note: The map function returns a List. If you'd like to use it as a vararg parameter, you can achieve that using toTypedArray() and a spread operator *. Code As follows:

val varargArray = textFields.map { it.text.toString() }.toTypedArray()
myFunction(*varargArray)

private fun myFunction(vararg list: String) {}

Upvotes: 2

Related Questions