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.1 Development Essentials – Java Edition

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

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

Table of Contents (88) 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. Creating and Managing Overflow Menus on Android 43. An Introduction to MotionLayout 44. An Android MotionLayout Editor Tutorial 45. A MotionLayout KeyCycle Tutorial 46. Working with the Floating Action Button and Snackbar 47. Creating a Tabbed Interface using the TabLayout Component 48. Working with the RecyclerView and CardView Widgets 49. An Android RecyclerView and CardView Tutorial 50. A Layout Editor Sample Data Tutorial 51. Working with the AppBar and Collapsing Toolbar Layouts 52. An Android Studio Master/Detail Flow Tutorial 53. An Overview of Android Intents 54. Android Explicit Intents – A Worked Example 55. Android Implicit Intents – A Worked Example 56. Android Broadcast Intents and Broadcast Receivers 57. A Basic Overview of Threads and AsyncTasks 58. An Overview of Android Started and Bound Services 59. Implementing an Android Started Service – A Worked Example 60. Android Local Bound Services – A Worked Example 61. Android Remote Bound Services – A Worked Example 62. An Android Notifications Tutorial 63. An Android Direct Reply Notification Tutorial 64. Foldable Devices and Multi-Window Support 65. An Overview of Android SQLite Databases 66. The Android Room Persistence Library 67. An Android TableLayout and TableRow Tutorial 68. An Android Room Database and Repository Tutorial 69. Accessing Cloud Storage using the Android Storage Access Framework 70. An Android Storage Access Framework Example 71. Video Playback on Android using the VideoView and MediaController Classes 72. Android Picture-in-Picture Mode 73. An Android Picture-in-Picture Tutorial 74. Making Runtime Permission Requests in Android 75. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 76. Working with the Google Maps Android API in Android Studio 77. Printing with the Android Printing Framework 78. An Android HTML and Web Content Printing Example 79. A Guide to Android Custom Document Printing 80. An Introduction to Android App Links 81. An Android Studio App Links Tutorial 82. A Guide to the Android Studio Profiler 83. An Android Biometric Authentication Tutorial 84. Creating, Testing and Uploading an Android App Bundle 85. An Overview of Android Dynamic Feature Modules 86. An Android Studio Dynamic Feature Tutorial 87. An Overview of Gradle in Android Studio Index

15. Saving and Restoring the State of an Android Activity

If the previous few chapters have achieved their objective, it should now be a little clearer as to the importance of saving and restoring the state of a user interface at particular points in the lifetime of an activity.

In this chapter, we will extend the example application created in “Android Activity State Changes by Example” to demonstrate the steps involved in saving and restoring state when an activity is destroyed and recreated by the runtime system.

A key component of saving and restoring dynamic state involves the use of the Android SDK Bundle class, a topic that will also be covered in this chapter.

15.1 Saving Dynamic State

An activity, as we have already learned, is given the opportunity to save dynamic state information via a call from the runtime system to the activity’s implementation of the onSaveInstanceState() method. Passed through as an argument to the method is a reference to a Bundle object into which the method will need to store any dynamic data that needs to be saved. The Bundle object is then stored by the runtime system on behalf of the activity and subsequently passed through as an argument to the activity’s onCreate() and onRestoreInstanceState() methods if and when they are called. The data can then be retrieved from the Bundle object within these methods and used to restore the state of the activity.

15.2 Default Saving of User Interface State

In the previous chapter, the diagnostic output from the StateChange example application showed that an activity goes through a number of state changes when the device on which it is running is rotated sufficiently to trigger an orientation change.

Launch the StateChange application once again, this time entering some text into the EditText field prior to performing the device rotation (on devices or emulators running Android 9 or later it may be necessary to tap the rotation button in the located in the status bar to complete the rotation). Having rotated the device, the following state change sequence should appear in the Logcat window:

onPause

onStop

onSaveInstanceState

onDestroy

onCreate

onStart

onRestoreInstanceState

onResume

Clearly this has resulted in the activity being destroyed and re-created. A review of the user interface of the running application, however, should show that the text entered into the...

15.3 The Bundle Class

For situations where state needs to be saved beyond the default functionality provided by the user interface view components, the Bundle class provides a container for storing data using a key-value pair mechanism. The keys take the form of string values, while the values associated with those keys can be in the form of a primitive value or any object that implements the Android Parcelable interface. A wide range of classes already implements the Parcelable interface. Custom classes may be made “parcelable” by implementing the set of methods defined in the Parcelable interface, details of which can be found in the Android documentation at:

https://developer.android.com/reference/android/os/Parcelable.html

The Bundle class also contains a set of methods that can be used to get and set key-value pairs for a variety of data types including both primitive types (including Boolean, char, double and float values) and objects (such as Strings and...

15.4 Saving the State

The first step in extending the StateChange application is to make sure that the text entered by the user is extracted from the EditText component within the onSaveInstanceState() method of the MainActivity activity, and then saved as a key-value pair into the Bundle object.

In order to extract the text from the EditText object we first need to identify that object in the user interface. Clearly, this involves bridging the gap between the Java code for the activity (contained in the MainActivity.java source code file) and the XML representation of the user interface (contained within the activity_main.xml resource file). In order to extract the text entered into the EditText component we need to gain access to that user interface object.

Each component within a user interface has associated with it a unique identifier. By default, the Layout Editor tool constructs the id for a newly added component from the object type. If more than one view of the same...

15.5 Restoring the State

The saved dynamic state can be restored in those lifecycle methods that are passed the Bundle object as an argument. This leaves the developer with the choice of using either onCreate() or onRestoreInstanceState(). The method to use will depend on the nature of the activity. In instances where state is best restored after the activity’s initialization tasks have been performed, the onRestoreInstanceState() method is generally more suitable. For the purposes of this example we will add code to the onRestoreInstanceState() method to extract the saved state from the Bundle using the “savedText” key. We can then display the text on the editText component using the object’s setText() method:

@Override

protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {

   super.onRestoreInstanceState(savedInstanceState);

   Log.i(TAG, "onRestoreInstanceState");

 

&...

15.6 Testing the Application

All that remains is once again to build and run the StateChange application. Once running and in the foreground, touch the EditText component and enter some text before rotating the device to another orientation. Whereas the text changes were previously lost, the new text is retained within the editText component thanks to the code we have added to the activity in this chapter.

Having verified that the code performs as expected, comment out the super.onSaveInstanceState() and super.onRestoreInstanceState() calls from the two methods, re-launch the app and note that the text is still preserved after a device rotation. The default save and restoration system has essentially been replaced by a custom implementation, thereby providing a way to dynamically and selectively save and restore state within an activity.

15.7 Summary

The saving and restoration of dynamic state in an Android application is simply a matter of implementing the appropriate code in the appropriate lifecycle methods. For most user interface views, this is handled automatically by the Activity super class. In other instances, this typically consists of extracting values and settings within the onSaveInstanceState() method and saving the data as key-value pairs within the Bundle object passed through to the activity by the runtime system.

State can be restored in either the onCreate() or the onRestoreInstanceState() methods of the activity by extracting values from the Bundle object and updating the activity based on the stored values.

In this chapter, we have used these techniques to update the StateChange project so that the Activity retains changes through the destruction and subsequent recreation of an activity.

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 2021 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}