简体   繁体   中英

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

            }
        });

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];
       // ...
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM