为什么当我从EditText中删除全部内容时,应用程序会崩溃?

huangapple go评论91阅读模式
英文:

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

问题

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

    }
});
英文:

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

            }
        });

答案1

得分: 1

你在afterTextChanged中访问第一个字符,如果你删除了所有的文本,数组的大小就是0。

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

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

答案2

得分: 0

应用程序崩溃是因为您正在访问一个没有任何元素的数组的第一个元素。

当您在清除文本后调用 characters[0] 时,数组 characters 是空的,因此会抛出一个越界异常。

您应该考虑数组为空的情况。

英文:

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.

huangapple
  • 本文由 发表于 2020年4月6日 21:36:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/61061127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定