Android Data Binding — Complete Guide
In this tutorial, you'll learn about Android Data Binding. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Data Binding XML expressions crash at runtime, @{user.name} produces null strings instead of hiding views, and two-way binding causes infinite loops.
Wrong Approach ❌
<!-- No null handling in binding expression -->
<TextView
android:text="@{user.address.street}"
android:visibility="@{user.isAdmin ? View.VISIBLE : View.GONE}"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
// Missing @Bindable annotation
class User {
var name: String = ""
get() = field
set(value) {
field = value
notifyPropertyChanged(BR.name) // BR.name won't exist!
}
}
Output: NullPointerException when user.address is null. BR.name generation fails.
Right Approach ✅
<TextView
android:text="@{user.address != null ? user.address.street : @string/unknown}"
android:visibility="@{user.isAdmin ? View.VISIBLE : View.GONE}"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
class User : BaseObservable() {
@get:Bindable
var name: String = ""
set(value) {
field = value
notifyPropertyChanged(BR.name)
}
}
Output: Safe expressions with null guards. Proper BR field generation via @Bindable.
Prevention
- Always null-check nested properties in XML expressions.
- Always annotate getters with
@get:BindableinBaseObservableclasses. - Use
Android:defaultValuefor two-way binding with text fields. - Enable
dataBinding = trueinbuild.gradleper module.
Common Mistakes with data binding
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro