原代码:
btn_realm_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Student student = new Student();
student.setNum(et_realm_num.getText().toString());
student.setName(et_realm_name.getText().toString());
student.setAge(Integer.parseInt(et_realm_age.getText().toString()));
mRealm.addStudent(student);
List<Student> studentList = mRealm.findAllStudent();
mRealmList.clear();
mRealmList.addAll(studentList);
realmAdapter.notifyDataSetChanged();
Log.e("bendi", "------add--------" + mRealmList.size());
}
});
报错:👇👇
java.lang.NumberFormatException: Invalid int: ""
错误原因:不能成功转成int类型
解决方法:就我的代码而言,student.setAge()中是从一个EditText中获取数据,并且我的EditText中有hint(提示文字:年龄),因此在获取编辑框中的数据时,当我没有输入任何数据,会出现获取hint文字的情况,此时将会出错,因为不能将文字转换为int类型。故,将以下代码块放置于try{}catch (Exception ignored){}中,增加其容错性。
故,修改后的代码如下:👇👇👇
btn_realm_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Student student = new Student();
student.setNum(et_realm_num.getText().toString());
student.setName(et_realm_name.getText().toString());
student.setAge(Integer.parseInt(et_realm_age.getText().toString()));
mRealm.addStudent(student);
List<Student> studentList = mRealm.findAllStudent();
mRealmList.clear();
mRealmList.addAll(studentList);
realmAdapter.notifyDataSetChanged();
Log.e("bendi", "------add--------" + mRealmList.size());
}
catch (Exception ignored){
// do sth. after error occurred
}
}
});
2020-11-13更新
应该先判断从EditText中获取的值是否为空,并且判断其是否为纯数字【一般会在xml对该EditText限制InputType】,而后再转为int类型。
网友评论