In many of the already existing Android applications when it comes to the forms, where it includes user details. If the user enters the wrong information to the text fields or if the user leaves the text fields without filling it, there is a need to provide certain alert information to the TextFields which are unfilled and which contain the wrong information. So in this article, it’s been discussed step by step how to give the error texts to the user. Have a look at the following image to get an idea about what has to implement in this discussion. Note that we are going to implement this project using the Java language.
In this discussion, two sample activities are taken for demonstration purposes, because in the first activity the text fields are implemented. If all the data entered in the text fields match the requirements then the user should proceed to the next activity.
Steps for Implementing form Validation in Android
Step 1: Create an empty activity project
- Create an empty activity Android Studio project. And select the programming language as JAVA.
- Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity android studio project.
Step 2: Working with the activity_main.xml
- Here in this case for demonstration purposes, only four text fields are implemented those are, First Name, Last Name, Email, and Password.
- Invoke the following code inside the activity_main.xml file.
Step 3: Create another empty activity
- Create another empty activity with activity_main2.xml and invoke the following code, which contains a simple text “Activity 2” to avoid confusion.
- The user should proceed to this activity, only when the user enters the data properly in the text fields given in the first activity.
Step 4: Working with the MainActivity.java file
- Here for the instance of the EditText class, setError() is to be called.
When the data filled in the text filed is wrong ->
// this gives error message to perticular text fild
// which contains the wrong data.
When user data is corrected by the user ->
// There is no need to give the error message when the user
// corrects wrongly entered text field.
- Invoke the following code. Comments are added for better understanding.