Data types that can be added to a Bundle object include primitives, like Int, or small, simple objects, like String. In an Android app, you’ll have not only primitives or Strings but also more complex data types. For example, storing a user profile in a data class:
data class UserProfile(val name: String, val nickName: String, val age: Int)
To add a UserProfile object to a Bundle, you must make the UserProfile object parcelable. To achieve this, you add the @Parcelize annotation to the UserProfile data class:
@Parcelize
data class UserUserProfile(val name: String, val nickName: String, val age: Int): Parcelable
Then you save a UserProfile in a composable function like this:
@Composable
fun UserProfileScreen(){
val userProfile by rememberSaveable {
mutableStateOf(UserProfile(name = "Bilbo Baggins", nickName = "Bilbo", age = 131))
}
...
}
If you can’t use the Parcelize interface to save the state, you can create a custom saver object using either mapSaver or listSaver functions. These functions let you define your own rules that will convert an object to a set of values that can be added to the Bundle object.
You’d use the mapSaver function to represent your class as a map of values that can be saved individually. The listSaver function lets you represent your class as a list of values.
Here’s an example of saving a UserProfile object using the listSaver function:
data class UserProfile(val name: String, val nickName: String, val age: Int)
// 1
val ProfileSaver = listSaver<UserProfile, Any>(
// 2
save = { listOf(it.name, it.nickName, it.age) },
// 3
restore = { UserProfile(name = it[0] as String, nickName = it[1] as String, age = it[2] as Int) }
)
In the code above:
You create a ProfileSaver object using the listSaver function.
The save lambda converts the UserProfile object to a list of items that will be added to the Bundle object individually.
The restore lambda creates a UserProfile object from the list of items.
Then you use the saver to save a UserProfile object across configuration changes like this:
@Composable
fun UserProfileScreen() {
val userProfile by rememberSaveable(stateSaver = ProfileSaver) {
mutableStateOf(UserProfile(name = "Bilbo Baggins", nickName = "Bilbo", age = 131))
}
}
Now, you’ll create a custom object using the mapSaver function in a demo.
See forum comments
This content was released on Sep 10 2024. The official support period is 6-months
from this date.
In this lesson, you’ll learn techniques of saving data of different data types during a configuration change.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.