Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.2 Development Essentials - Java Edition

You're reading from  Android Studio 4.2 Development Essentials - Java Edition

Product type Book
Published in Aug 2021
Publisher Packt
ISBN-13 9781803238814
Pages 782 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (87) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Overview of Android View Binding 12. Understanding Android Application and Activity Lifecycles 13. Handling Android Activity State Changes 14. Android Activity State Changes by Example 15. Saving and Restoring the State of an Android Activity 16. Understanding Android Views, View Groups and Layouts 17. A Guide to the Android Studio Layout Editor Tool 18. A Guide to the Android ConstraintLayout 19. A Guide to Using ConstraintLayout in Android Studio 20. Working with ConstraintLayout Chains and Ratios in Android Studio 21. An Android Studio Layout Editor ConstraintLayout Tutorial 22. Manual XML Layout Design in Android Studio 23. Managing Constraints using Constraint Sets 24. An Android ConstraintSet Tutorial 25. A Guide to using Apply Changes in Android Studio 26. An Overview and Example of Android Event Handling 27. Android Touch and Multi-touch Event Handling 28. Detecting Common Gestures Using the Android Gesture Detector Class 29. Implementing Custom Gesture and Pinch Recognition on Android 30. An Introduction to Android Fragments 31. Using Fragments in Android Studio - An Example 32. Modern Android App Architecture with Jetpack 33. An Android Jetpack ViewModel Tutorial 34. An Android Jetpack LiveData Tutorial 35. An Overview of Android Jetpack Data Binding 36. An Android Jetpack Data Binding Tutorial 37. An Android ViewModel Saved State Tutorial 38. Working with Android Lifecycle-Aware Components 39. An Android Jetpack Lifecycle Awareness Tutorial 40. An Overview of the Navigation Architecture Component 41. An Android Jetpack Navigation Component Tutorial 42. An Introduction to MotionLayout 43. An Android MotionLayout Editor Tutorial 44. A MotionLayout KeyCycle Tutorial 45. Working with the Floating Action Button and Snackbar 46. Creating a Tabbed Interface using the TabLayout Component 47. Working with the RecyclerView and CardView Widgets 48. An Android RecyclerView and CardView Tutorial 49. A Layout Editor Sample Data Tutorial 50. Working with the AppBar and Collapsing Toolbar Layouts 51. An Android Studio Primary/Detail Flow Tutorial 52. An Overview of Android Intents 53. Android Explicit Intents – A Worked Example 54. Android Implicit Intents – A Worked Example 55. Android Broadcast Intents and Broadcast Receivers 56. A Basic Overview of Java Threads, Handlers and Executors 57. An Overview of Android Services 58. Implementing an Android Started Service – A Worked Example 59. Android Local Bound Services – A Worked Example 60. Android Remote Bound Services – A Worked Example 61. An Android Notifications Tutorial 62. An Android Direct Reply Notification Tutorial 63. Foldable Devices and Multi-Window Support 64. An Overview of Android SQLite Databases 65. The Android Room Persistence Library 66. An Android TableLayout and TableRow Tutorial 67. An Android Room Database and Repository Tutorial 68. Accessing Cloud Storage using the Android Storage Access Framework 69. An Android Storage Access Framework Example 70. Video Playback on Android using the VideoView and MediaController Classes 71. Android Picture-in-Picture Mode 72. An Android Picture-in-Picture Tutorial 73. Making Runtime Permission Requests in Android 74. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 75. Working with the Google Maps Android API in Android Studio 76. Printing with the Android Printing Framework 77. An Android HTML and Web Content Printing Example 78. A Guide to Android Custom Document Printing 79. An Introduction to Android App Links 80. An Android Studio App Links Tutorial 81. A Guide to the Android Studio Profiler 82. An Android Biometric Authentication Tutorial 83. Creating, Testing and Uploading an Android App Bundle 84. An Overview of Android Dynamic Feature Modules 85. An Android Studio Dynamic Feature Tutorial 86. An Overview of Gradle in Android Studio Index

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.1.0"

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

.

.

}

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.2 Development Essentials - Java Edition
Published in: Aug 2021 Publisher: Packt ISBN-13: 9781803238814
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.
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}