validate the edittext field inside alertdialog
I am using this function to insert into the database. I'd like to validate inputs from two edittext fields. Whenever I push ok button without giving any inputs, the program crashes.I tried to print the values as well, but it didnt display in logcat.Am i doing anything wrong?
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 Dialog开发者_StackOverflowInterface.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();
}
You are calling editBlah.getText().toString() which can return "";
When parsing this to an integer an Exception will be thrown.
( It could also be, if you call .getText() on a view which has initialised to null (ie, you have incorrectly specified the id for the ID you want) a NullPointerException will be thrown. Without the Stacktrace you wouldn't be able to tell which - try and post your stack trace with the question where possible ).
You're question is correct - What you need to do is validate the input you're getting: ie:
int year = Integer.parseInt( editYear.getText().toString() );
should be:
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.
}
Or even the following if you are already going to be validating your int values:
int year = Integer.parseInt( editYear.getText().toString().equalsIgnoreCase("") ?
"-1" : editYear.getText().toString());
editCountry.getText() equals with nullstring? nullponterexception
精彩评论