Stefan Chiriacopol
Stefan Chiriacopol

Reputation: 23

Why is the app crashing when I delete all from the EditText?

I programmed my imageTextView to show the first letter of the prenumeString, got from the edit text. The problem is that whenever all the letter are raised from the Edit Text, the app crashes. Any ideas?

Code:

prenume.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                prenumeString = prenume.getText().toString();
                char[] characters = prenumeString.toCharArray();
                char firstChar = characters[0];
                imageTextView.setText(String.valueOf(firstChar));
                //TODO: Debug the error from letter showing

            }
        });

Upvotes: 0

Views: 390

Answers (2)

k5_
k5_

Reputation: 5568

You access the first character in afterTextChanged, if you delete all text the array is size 0.

    char[] characters = prenumeString.toCharArray();
    if (characters.length != 0){
       char firstChar = characters[0];
       // ...
    }

Upvotes: 1

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16224

The app crashes because you are accessing the first element of an array which has zero elements.

When you are calling characters[0] after clearing the text, the array characters is empty, so an out-of-bounds exception is thrown.

You should consider the case in which the array is empty.

Upvotes: 0

Related Questions