Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

37. An Android ViewModel Saved State Tutorial

The preservation and restoration of app state is all about presenting the user with continuity in terms of appearance and behavior after an app is placed into the background. Users have come to expect to be able to switch from one app to another and, on returning to the original app, to find it in the exact state it was in before the switch took place.

As outlined in the chapter entitled “Understanding Android Application and Activity Lifecycles”, when the user places an app into the background that app becomes eligible for termination by the operating system in the event that resources become constrained. When the user attempts to return the terminated app to the foreground, Android simply relaunches the app in a new process. Since this is all invisible to the user, it is the responsibility of the app to restore itself to the same state it was in when the app was originally placed in the background instead of presenting...

37.1 Understanding ViewModel State Saving

As outlined in the previous chapters, the ViewModel brings many benefits to app development, including UI state restoration in the event of configuration changes such as a device rotation. To see this in action, run the ViewModelDemo app (or if you have not yet created the project, load into Android Studio the ViewModelDemo_LiveData project from the sample code download that accompanies the book).

Once running, enter a dollar value and convert it to euros. With both the dollar and euro values displayed, rotate the device or emulator and note that, once the app has responded to the orientation change, both values are still visible.

Unfortunately, this behavior does not extend to the termination of a background app process. With the app still running, tap the device home button to place the ViewModelDemo app into the background, then terminate it by opening the Logcat tool window in Android Studio and clicking on the terminate button as...

37.2 Implementing ViewModel State Saving

Basic ViewModel state saving is made possible through the introduction of the ViewModel Saved State library. This library essentially extends the ViewModel class to include support for maintaining state through the termination and subsequent relaunch of a background process.

The key to saving state is the SavedStateHandle class which is used to save and restore the state of a view model instance. A SavedStateHandle object contains a key-value map that allows data values to be saved and restored by referencing corresponding keys.

To support saved state, a different kind of ViewModel subclass needs to be declared, in this case one containing a constructor which can receive a SavedStateHandle instance. Once declared, ViewModel instances of this type can be created by including a SavedStateViewModelFactory object at creation time. Consider the following code excerpt from a standard ViewModel declaration:

package com.ebookfrenzy.viewmodeldemo...

37.3 Saving and Restoring State

An object or value can be saved from within the ViewModel by passing it through to the set() method of the SavedStateHandle instance, providing the key string by which it is to be referenced when performing a retrieval:

private static final String NAME_KEY = "Customer Name";

 

savedStateHandle.set(NAME_KEY, customerName;

When used with LiveData objects, a previously saved value may be restored using the getLiveData() method of the SavedStateHandle instance, once again referencing the corresponding key as follows:

MutableLiveData<String> restoredName = savedStateHandle.getLiveData(NAME_KEY);

To restore a normal (non-LiveData) object, simply use the SavedStateHandle get() method:

String restoredName = savedStateHandle.get(NAME_KEY);

Other useful SavedStateHandle methods include the following:

contains(String key) - Returns a boolean value indicating whether the saved state contains a value for the...

37.4 Adding Saved State Support to the ViewModelDemo Project

With the basics of ViewModel Saved State covered, the ViewModelDemo app can be extended to include this support. Begin by loading the ViewModelDemo_LiveData project created in “An Android Jetpack LiveData Tutorial” into Android Studio (a copy of the project is also available in the sample code download), opening the build.gradle (Module: ViewModelDemo.app) file and adding the Saved State library dependencies (checking, as always, if more recent library versions are available):

.

.

dependencies {

.

.

    implementation "androidx.savedstate:savedstate:1.0.0"

    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0"

.

.

}

Next, modify the MainViewModel.java file so that the constructor accepts and stores a SavedStateHandle instance. Also import androidx.lifecycle.SavedStateHandle, declare a key string...

37.5 Summary

A well designed app should always present the user with the same state when brought forward from the background, regardless of whether the process containing the app was terminated by the operating system in the interim. When working with ViewModels this can be achieved by taking advantage of the ViewModel Saved State module. This involves modifying the ViewModel constructor to accept a SavedStateHandle instance which, in turn, can be used to save and restore data values via a range of method calls. When the ViewModel instance is created, it must be passed a SavedStateViewModelFactory instance. Once these steps have been implemented, the app will automatically save and restore state during a background termination.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth