我正在使用此功能插入数据库。我想验证来自两个edittext字段的输入。每当我按下ok按钮而不提供任何输入时,程序崩溃。我也尝试打印这些值,但它没有显示在logcat中。我做错了什么?
private void add() {
LayoutInflater inflater=LayoutInflater.from(this);
final View addView=inflater.inflate(R.layout.add_country, null);
new AlertDialog.Builder(this)
.setTitle("Add new country/year")
.setView(addView)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClickDialogInterface dialog,int whichButton) {
/* Read alert input */
EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
String country = editCountry.getText().toString();
EditText editYear =(EditText)addView.findViewById(R.id.editYear);
int year = Integer.parseInt( editYear.getText().toString() );
if(editCountry.getText().toString().trim().length()>0 && editYear.getText().toString().trim().length()>0){
/* Open DB and add new entry */
db.open();
db.insertEntry(country,year);
/* Create new cursor to update list. Must be possible to handle
* in a better way. */
entryCursor = db.fetchAllEntries(); // all country/year pairs
adapter = new SimpleCursorAdapter(CountryEditor.this,
R.layout.country_row,entryCursor,
new String[] {"country", "year"},
new int[] {R.id.country, R.id.year});
setListAdapter(adapter);
db.close();
}
else{
Toast.makeText(CountryEditor.this,
"You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
// ignore, just dismiss
}
})
.show();
}
答案 0 :(得分:1)
您正在调用editBlah.getText()。toString(),它可以返回“”;
将此解析为整数时,将抛出异常。
(也可能是,如果你在一个初始化为null的视图上调用.getText()(即你错误地指定了你想要的ID的id),将抛出NullPointerException。 Stacktrace你无法分辨哪一个 - 尝试并尽可能用问题发布你的堆栈跟踪。
你的问题是正确的 - 你需要做的是验证你得到的输入:即:
int year = Integer.parseInt( editYear.getText().toString() );
应该是:
if(editYear.getText().toString().equalsIgnoreCase("")) {
// Cannot parse into an int therefore perform some action which will notify the
// user they haven't entered the correct value.
}
如果你已经要验证你的int值,甚至是以下内容:
int year = Integer.parseInt( editYear.getText().toString().equalsIgnoreCase("") ?
"-1" : editYear.getText().toString());
答案 1 :(得分:1)
editCountry.getText()等于nullstring? nullponterexception