What is the best practice for checking in an EditText for any values before my onclick from a button is fired off. When its fired off now with no value it errors out and crashes. I tried to do a if(edittext != null){then my onlcick code} and it still crashed when I clicked it after no value in the edittext.
Share
The reason why
if (edittext != null) {...}does not work is because this statement will check for a condition on the actualEditTextobject, and not its contents.If you’re after the contents, simply call
edittext.getText()and apply your validation logic to that. There’s a convenience method inTextUtilsthat you can use to check whether the text isnullor empty (""):TextUtils.isEmpty(edittext.getText()). You can use it for plain Java strings too, e.g.Which will trim leading and trailing spaces first, before the test. Depending on your requirements, you can extend this easily with a regular expression to strip out any white space character etc. As a general tip: search around for “android form validation” and I’m sure you’ll find more pointers.