Reputation: 1720
I created a Dialog with a TextEdit as a number input to convert it to a double value. I want to prevent an exception by checking, if the TextEdit input is empty but it always jumps to the else statement and therefore creates an exception when the EditText is blank.
final Builder builder = new Builder(this);
final EditText input = new EditText(this);
input.setKeyListener(DigitsKeyListener.getInstance(false, true));
builder
.setTitle(R.string.dialog_title_addmark)
.setMessage(R.string.dialog_addmark)
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (input.toString().trim().length() == 0) {
Toast.makeText(Marks.this, R.string.input_empty, Toast.LENGTH_SHORT).show();
} else {
Double value = Double.valueOf(input.getText().toString());
db.insertMark(selection, value);
getData();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
I also tried it checking (input.toString() != null) but that does not work either.
Thanks for your help
Upvotes: 1
Views: 1292
Reputation: 24820
input.toString() will return the reference value of the Edittext not the text inside the Edittext.
Use below condition
if(input.getText().toString() != null || !input.getText().toString().isEmpty())
Upvotes: 0
Reputation: 785
If you want the text from a EditText
object, you should use the following line of code:
input.getText().tostring();
where input
is a EditText
-object.
Using the code
input.toString();
will give you a string representation of the object, and as long as the object is not null
, the toString of that object will be not null
, so using input.toString() != null
will not give you any useful information.
That means that you should do the following validation:
if (input.getText().toString().trim().length() == 0)
to figure out if the input object contains some text.
Upvotes: 1
Reputation: 6201
Try this way..
if (input.toString().trim().length()< 0) {
Toast.makeText(Marks.this, R.string.input_empty, Toast.LENGTH_SHORT).show();
} else {
Double value = Double.valueOf(input.getText().toString());
db.insertMark(selection, value);
getData();
}
Upvotes: 0