Alexander Vasilchuk
Alexander Vasilchuk

Reputation: 155

Filling array by values from EditText

I have EditText and array. I want fill array by values from EditText field. Something like:

final EditText edit_1= (EditText) findViewById(R.id.editText1);
int[] b = new int[8];
b[0] = first_character_from_EditText_field;
b[1] = second_character_from_EditText_field;
...

All the characters are digits. How can I achieve this?

Upvotes: 1

Views: 209

Answers (1)

Farshad
Farshad

Reputation: 3140

You need to get every input character and convert it to int:

    EditText edit_1 = (EditText) findViewById(R.id.editText1);
    if (edit_1.getText().length() > 0) {
        int[] b = new int[edit_1.getText().length()];
        for (int i = 0; i < b.length; i++) {
            b[i] = Integer.parseInt(String.valueOf(edit_1.getText().charAt(i)));
        }

Remeber we're assuming that the input text only contains digits, You should handle the exception to prevent of app crash in case user enters other characters.

Upvotes: 1

Related Questions