Search⌘ K
AI Features

Data Validation and Error Handling

Explore how to validate user input and handle errors on an Android login screen. Learn to bind views, check input fields, display error messages, clear errors on text change, and show error dialogs to enhance user experience during login.

View binding #

To interact with views we need to bind the view from XML to Java objects via the findViewById method.

Note: You can only start binding views after the activity has been created and the content view has been set.

Java
public class LoginActivity extends AppCompatActivity {
private TextInputLayout textUsernameLayout;
private TextInputLayout textPasswordInput;
private Button loginButton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
textUsernameLayout = findViewById(R.id.textUsernameLayout);
textPasswordInput = findViewById(R.id.textPasswordInput);
loginButton = findViewById(R.id.loginButton);
}
}

Validation & error message #

To perform validation, we need to set a click listener on the login button via the setOnClickListener method, which accepts the OnClickListener interface as a parameter. When the login button is clicked, we execute our onLoginClicked method.

Java
public class LoginActivity extends AppCompatActivity {
...
private Button loginButton;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
...
loginButton = findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginActivity.this.onLoginClicked();
}
});
}
private void onLoginClicked() {
// not implemented yet
}
}

Click listener can be slightly simplified to lambda because we use Java 8.

Java
loginButton = findViewById(R.id.loginButton);
loginButton.setOnClickListener(v -> onLoginClicked());

Now, we can implement ...