Android Programming In Kotlin: State Management
Written by Mike James   
Monday, 11 March 2019
Article Index
Android Programming In Kotlin: State Management
Complex UI Elements

There is no reason not to use the onCreate event handler in this way, but the system also fires an onResetoreInstanceState event when it is about to perform its own "automatic" restore of the UI for you. You can override this event handler if you want to keep the code that restores the app’s state kept out of the onCreate event handler.

For example, you could have written:

override fun onRestoreInstanceState(
savedInstanceState: Bundle?) { if (savedInstanceState != null) { textView.text =
savedInstanceState.getCharSequence("myText") } super.onRestoreInstanceState(savedInstanceState) }

Do remember to call the super.onRestoreInstanceState if you want the system to restore the rest of the UI in the usual way. There are put and get methods for a range of standard data types. All simple types, byte, integer and so on, are supported, as are strings, arrays and other simple data structures. You can also create your own classes that can be stored in a Bundle by implementing the Parcelable interface. Notice you can save arbitrary data, and not just data for the layout. You can also create your own Bundle instance and make use of it for data storage, persistence and for transferring data to other parts of a program. There are many standard classes the Bundle doesn't support. In these cases you have to make your own arrangements to save data to storage. 

Often all you need to do to make sure that your app maintains its state between system restarts is to use the savedInstanceState Bundle object. This approach also reduces much of the practicality of lifecycle management to implementing the onSaveInstanceState and onRestoreInstanceState event handlers. This is so much simpler than having to worry about all of the different life cycle events. 

As an exercise, you can now go back to the iCalc example in Chapter 3 and make its display and current value persist through a screen rotate.

Complex UI Elements

One of the traps waiting for you is the problem of exactly what is automatically saved and restored. For example, at the start of this chapter we had the story of the app that lost the user’s form data when it was rotated. Given what we now know of the auto-saving and restoration of user modifiable UI elements, you might be wondering how this could happen?

The answer is that the programmers of the app had probably grown accustomed to the automatic persistence of UI state and didn't bother to check that rotation had no effect. It did have an effect because the form was being downloaded from a website and displayed in a WebView control. A WebView control is persisted by the system, but it reloads the page when it is restored. This means that on a rotation the form was reloaded as empty and the user’s data was lost.

  • You always have to check that things work as you expect. Always test what happens to your UI on a rotation.  

 

Advanced State Management

For completeness it is worth noting that there are many more approaches to maintaining state. Later you will need to discover how to store lots of user data locally for longer term persistence, and this is often enough to implement state management though a configuration change.

There are also more advanced state management problems when you come to make use of Fragments, the subject of Android Programming: Mastering Fragments & Dialogs. In this case you can use retainedInstance to ask the system not to destroy an entire Fragment. This means that all of the data stored in the Fragment is retained even though the Activity may be removed from memory. This makes it possible to use a Fragment as a repository of state. 

The ultimate in making sure that things happen as you want is to handle the configuration change yourself. You can do this by making a change to the manifest. If you do this then it is up to you to make the changes needed when the onConfigurationChanged event occurs. You could, for example, opt to animate buttons and other UI objects into new positions or just ignore the need to reconfigure altogether. 

This is all advanced and for most applications you can get by using just the onSaveInstanceState and onRestoreInstanceState event handlers.

Summary

  • Android, like many other mobile OSs, will remove your app from memory and restart it as it needs to. 

  • The user will not be aware that your app has been destroyed and recreated and will expect it to continue from where they left off.

  • The system signals changes in state to your Activity via a complicated set of events. You need to understand how these work in order to make your Activity resume correctly after the various levels of suspension.

  • onCreate should not be regarded as the “constructor” for your app because it is called when the app is restored as well as when it is run for the first time. 

  • The system will store the state of any user modifiable UI components and restore it when the Activity resumes.

  • The data is stored in a special instance of a Bundle, a set of key/value pairs, called savedInstanceState.

  • The system alerts you when it is about to save and restore data from savedInstanceState by firing the onSaveInstanceState and onRestoreInstanceState event handlers.

  • You can override both of these event handlers to save and restore extra data in the savedInstanceState Bundle.

  • For many simple apps you can mostly ignore the lifecycle events and concentrate on using the onSaveInstanceState and onRestoreInstanceState event handlers to persist data.

  • You must always check that UI and other elements are persisted through a suspension of your app. You can test using a rotation configuration change.

  • There are other more advanced ways of saving state which you will need to discover later on. You can't use a Bundle for everything.

 

 

Android Programming In Kotlin
Starting with an App

Covers Android Studio 3 and Constraint Layout.

Is now available as a print book:

coverKotlinsmall

Buy from: Amazon

Contents

  1. Getting Started With Android Studio 3
  2. The Activity And The UI
        Extract: Activity & UI  
  3. Building The UI and a Calculator App
        Extract: A First App
  4. Android Events
  5. Basic Controls
        Extract Basic Controls
        Extract More Controls ***NEW!
  6. Layout Containers
        Extract Layouts - LinearLayout
  7. The ConstraintLayout 
        Extract Bias & Chains
  8. Programming The UI
        Extract Programming the UI
        Extract Layouts and Autonaming Components
  9. Menus & The Action Bar
  10. Menus, Context & Popup
  11. Resources
        Extract Conditional Resources
  12. Beginning Bitmap Graphics
        Extract Animation
  13. Staying Alive! Lifecycle & State
        Extract  State Managment
  14. Spinners
  15. Pickers
  16. ListView And Adapters
  17. Android The Kotlin Way

If you are interested in creating custom template also see:

Custom Projects In Android Studio

Androidgears

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

kotlin book

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962544>

<ASIN:1871962536>

 



Last Updated ( Wednesday, 13 March 2019 )