Validating Input

After you’ve created your application so that users can enter information, and perhaps you’ve already created the mechanism to save the content to a database or remote server, what happens when the user enters invalid text or no text? Input validation now enters the picture.

Input validation verifies the input before the save takes place. If a user enters no text for the title or the message and attempts to save, should she be allowed to? Of course not.

The method in which you provide validation to the user is up to you. Here are some common methods:

check.png EditText.setError(): If you detect that the user has tried to enter invalid text in a field, simply call setError() and pass the error message. Android then decorates EditText with an error icon and displays an error message. The message stays onscreen until the user changes the value of the field or until you call setError(null).

check.png TextWatcher: Implement a TextWatcher on the EditText view. This class provides callbacks to you every time the text changes in the EditText view. Therefore, you can inspect the text on each keystroke.

check.png On Save: When the user attempts to save a form, inspect all the form fields at that time and ...

Get Android Application Development For Dummies, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.