Search⌘ K
AI Features

Data Validation and Error Handling

Explore how to implement data validation and error handling in an Android login screen using Kotlin. Learn to check user input, display error messages, clear them on text changes, and show dialogs for invalid credentials to create a smooth login experience.

View binding

Because we are going to use view references across different methods, we need to declare binding as a global variable (1).

Kotlin
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding // 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}

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.

Kotlin
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.loginButton.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
onLoginClicked()
}
})
}
}

Click listener anonymous object implementation (1) can be slightly simplified to anonymous function (2) or lambda (3).

In Kotlin, if lambda is the last parameter it can be moved outside function parentheses (4). ...