0

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.

4
  • 1
    I think people have downvoted cause you did not provide/show any attempt or research effort. Is a for-loop not enough minimal ? Commented Apr 17, 2018 at 13:19
  • @vincrichaud Yes, I agree with your comment. I do think so. Commented Apr 17, 2018 at 13:21
  • 1
    @vincrichaud minimal enough to fit as a parameter in a function. I'll edit the original question. Commented Apr 17, 2018 at 13:27
  • Perfectly valid question now, +1 ... Commented Apr 17, 2018 at 13:33

1 Answer 1

2

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) {}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is what I wanted. Also, I need to mention, I'm using varargs as a parameter. So also should mention that use case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.