How to save the instance in case of configuration change while using DataBinding

Updated 28 June 2018

Save

It may look difficult to deal with the configuration changes and save the instance in Android but it is not. There are few scenarios in which the Activity gets destroyed and needs to be recreated and also the data need to be restored again and for this, the instance is always saved before destroying the activity. There are both types techniques in which Android automatically manages the data or you can do it manually. But it is recommended that you should manage the data manually. So that there will not be any issues or losses.

Let us see how to save data for configuration change while using data binding.

Suppose we are creating a login page. Consider the below-given class

The above Model contains two variables username and password and it also implements Parcelable because to save and retrieve the Object from memory. Although the edit texts automatically save the values all you need to do is give them an id. It is must for them to save the data.

This Model class will be used to save the values of username and password in the XML file of the activity. Below is the example of the activity_login.xml

We are using a two-way data binding in the above example so any changes in the edit text fields will be automatically updated to the model Object.

Now we have both the XML and the model class linked let us see how the object is assigned inside the Main Activity. Below is the example of the Main Activity class.

In the above code segment, you can see that we have assigned our model class to the Class binding object. But in this case, Whenever the configurations are changed then everytime a new object is being initialized to it. So the data will not be saved and we will get the blank fields again.

To get the data first we need to save the instance and then after the configuration change, we need to add the data from the savedInstanceState. Below is the example of saving the instance.

this will save the model object and when the activity is created again then it will be passed to the onCreate function and there you will check that if the savedInstanceState is not null then get the object from it and assign to the XML. Example of the above theory is given below.

That’s all!

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home