Your Second Kotlin Android App

Aug 29 2023 · Kotlin 1.8.21, Android 13, Android Studio Flamingo | 2022.2.1

Part 3: Save Preferences

21. Read & Save Tasks From SharedPreferences

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 20. Challenge: Create an Instance of ListDataManager Next episode: 22. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 21. Read & Save Tasks From SharedPreferences

You already have an instance of your ViewModel. In this episode, you’ll use it to read and save your todos.

Navigate to TaskListScreen and below your ViewModel instance, add the following code:

val viewModelTasks = taskListViewModel.readLists().toList()
var tasks by remember { mutableStateOf(viewModelTasks) }

Here, you’re creating a variable called viewModelTasks and assigning it the value of the readLists method from your ViewModel. You call toList() on this variable to return an immmutable collection of items. You’re also defining a state variable called tasks and assigning it the value of viewModelTasks. This is because you want to be able to update the tasks once you add new ones and update the view as well.

Next, replace emptyList() with tasks in the TaskListContent composable.

This now enables your TaskListContent to use the tasks from the view model.

Lastly, you need to save your tasks once the user taps Create in the AlertDialog. To do this, replace the // TODO save the task list with:

tasks = (tasks + TaskList(it))
taskListViewModel.saveList(TaskList(it))

In this code, you’re calling the saveList method from your ViewModel and passing in the task list. You’re also updating the tasks state variable with the new task list.

Build and run the app. Tab the floating action button and add a new task. You should see the new task in the list.