Going through state-saving management

If you paid attention to the OnCreate() method, you certainly must have noticed that we can restore data from a data structure named bundle when activities are put in the forefront after being killed or destroyed by the OS. However, at this time, we have not yet provided the mechanism to be used in order to save this data inside the Bundle data structure. In this recipe, we will show you how to manage the saving/loading methods and properties of the bundle.

Getting ready

Just as the earlier recipes of this chapter, the only requirement is to have Xamarin Studio or the Xamarin plugin for Visual Studio up and running and a successful understanding of the concepts covered in previous recipes.

How to do it...

The first method we have to implement is the OnSaveInstanceState() method, which, as a reminder, will be triggered right before the death of an activity. Let's consider a simple application, composed of four Text labels and four TextView elements asking the user to enter their name, address, phone number, and e-mail address. Taking into account that filling in this kind of form is really a pain with a virtual keyboard, it will be a good thing to restore already typed information if the user has to quit the application for any reason earlier. The following screenshot presents the application we just described. The application that save preferences:

How to do it...
  1. Add the following code sample to your MainActivity class (created in the previous recipe), in order to save the form's information into the bundle. As you can see, the Bundle accepts new entries in the form of key-value pairs. Therefore, we put four new keys _email, _name, _address, and _phone containing the values of the e-mail address, name, address, and phone number fields, respectively. As always, we also call the base implementation:
    protected override void OnSaveInstanceState(Bundle bundle) {
      bundle.PutString ("_email", FindViewById<TextView> (Resource.Id.mail).Text);
      bundle.PutString ("_name", FindViewById<TextView> (Resource.Id.name).Text);
      bundle.PutString ("_address", FindViewById<TextView> (Resource.Id.address).Text);
      bundle.PutString ("_phone", FindViewById<TextView> (Resource.Id.phone).Text);
      Log.Debug(GetType ().FullName, "OnSaveInstanceState Invoked");base.OnSaveInstanceState (bundle);
    }

    The preceding code sample contains the logging method. The logging methods can be separated on four levels. By level priority, these levels are debug, info, warn, and error, and they have to be used with a tag for the log. Here, we choose the class full name and the log itself. The log will be printed in the Xamarin Studio or the Visual Studio consoles. We encourage you to write such statements in order to identify the method invocation without using the step-by-step debugger, thus speeding up your development.

  2. Press the Home button of the virtual device, the following line appears in the Application Output Console:
    [Mail.MainActivity] OnSaveInstanceState Invoked

    Meaning that the OnSaveInstanceState() method has been executed and therefore, the field's text has been saved into the Bundle.

  3. Write the code enabling the restore of all our fields. For such a restore, the OnCreate() method throughout a conditional event linked to the Bundle's state could be the most suitable place to do it.
    protected override void OnCreate (Bundle bundle) {
      base.OnCreate (bundle);
      // Set our view from the "main" layout resource
      SetContentView (Resource.Layout.Main);
      if (bundle != null) {
        FindViewById<TextView> (Resource.Id.mail).Text = bundle.GetString ("_email");
        FindViewById<TextView> (Resource.Id.name).Text = bundle.GetString ("_name");
        FindViewById<TextView> (Resource.Id.address).Text = bundle.GetString ("_address");
        FindViewById<TextView> (Resource.Id.phone).Text = bundle.GetString ("_phone");
        Log.Debug(GetType ().FullName, "Bundle was not null.
        Restore complete.");
      }
    }

In the preceding code, we show how to get back our values from the Bundle. We will use the Get() method with the key in a parameter. Thus, we affect the field's text with their corresponding values. This code could also take place in an override of the OnRestoreInstanceState() method as shown by the following code:

protected override void OnRestoreInstanceState(Bundle bundle) {
  // Restore your data here
}

How it works...

The management of the Bundle is handled by two new On methods. These methods are OnSaveInstanceState() and OnRestoreInstanceState(), which are invoked before the destruction of an activity and after the OnCreate() execution, respectively.

The following screenshot presents the state management process with these two new methods for saving a state.

How it works...

As you can see, the OnRestoreInstanceState() method is called right after the end of the OnCreate() method, and the OnSaveInstanceState() method can be called at two different times. Indeed, the OnSaveInstanceState() method will be invoked during the planned destruction of an activity using the OnDestroy() method, and also when the OS kills your paused or stopped activities. Therefore, if these two methods are well overridden and correctly manage the save in/load from Bundle, they can restart like a charm even if the system kills your activities without any warnings.

There's more...

For a while, Android devices own two different buttons which seem to have the same behavior, these are the Back button and the Home button.

There's more...

The difference between these two buttons is, in reality, quite simple. The Home button tells the OS that the user needs to use another application, while using the Return button closes the application, meaning that the user is done with it. Therefore, the Home button will put activities in the background, that is, in the Stopped state, and the Return button will activate the destruction of activities by the system.

See also

Refer to Chapter 4, Using Android Resources, to learn how to prevent activity being stored by the state management mechanism.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.159.10