AI Features

Data Validation and Error Handling

This lesson will cover how to validate user input text and show error messages.

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.

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.

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.

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

Now, we can implement validation inside onLoginClicked method ...