英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论