An Android Jetpack Data Binding Tutorial

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
An Overview of Android Jetpack Data BindingWorking with Android Jetpack Lifecycle-Aware Components


You are reading a sample chapter from the Android Studio 3.2 Edition of this book.

Purchase the fully updated Android Studio 3.3 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format

Android Studio 3.3 Development Essentials - Android 9 Edition Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters and over 700 pages

Buy Print Preview Book


So far in this book we have covered the basic concepts of modern Android app architecture and looked in more detail at the ViewModel and LiveData components. The concept of data binding was also covered in the previous chapter and will now be used in this chapter to further modify the ViewModelDemo app.




Removing the Redundant Code

Before implementing data binding within the ViewModelDemo app, the power of data binding will be demonstrated by deleting all of the code within the project that will no longer be needed by the end of this chapter.

Launch Android Studio, open the ViewModelDemo project, edit the MainFragment.java file and modify the code as follows:

package com.ebookfrenzy.viewmodeldemo.ui.main;
 
import android.arch.lifecycle.ViewModelProviders;
 
import android.os.Bundle;
 
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import com.ebookfrenzy.viewmodeldemo.R;
 
public class MainFragment extends Fragment {
 
    private MainViewModel mViewModel;
.
.
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    }
}

Next, edit the MainViewModel.java file and continue deleting code as follows (note also the conversion of the dollarText variable to LiveData):

package com.ebookfrenzy.viewmodeldemo.ui.main;
 
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
 
public class  MainViewModel extends ViewModel {
 
    private static final Float usd_to_eu_rate = 0.74F;
    public MutableLiveData<String> dollarValue = new MutableLiveData<>();
    public MutableLiveData<Float> result = new MutableLiveData<>();
}

Though we‘ll be adding a few additional lines of code in the course of implementing data binding, clearly data binding has significantly reduced the amount of code that needed to be written.

Enabling Data Binding

The first step in using data binding is to enable it within the Android Studio project. This involves adding a new property to the Module level build.gradle file, so open this file (app -> Gradle Scripts -> build.gradle (Module: app)) as highlighted in Figure 35-1:


As 3.2 data binding gradle file.png


Within the build.gradle file, add the element shown below to enable data binding within the project:

apply plugin: 'com.android.application'
  
android {
  
    dataBinding {
        enabled = true
    }
    compileSdkVersion 28
.
.
}

Once the entry has been added, a yellow bar will appear across the top of the editor screen containing a Sync Now link. Click this to resynchronize the project with the new build configuration settings:


As 3.2 data binding gradle sync.png



Adding the Layout Element

As described in “An Overview of Android Jetpack Data Binding”, in order to be able to use data binding, the layout hierarchy must have a layout component as the root view. This requires that the following changes be made to the main_fragment.xml layout file (app -> res -> layout -> main_fragment.xml). Open this file in the layout editor tool, switch to Text mode and make these changes:

<?xml version="1.0" encoding="utf-8"?>
 
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
 
        <android.support.constraint.ConstraintLayout 
            android:id="@+id/main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".ui.main.MainFragment">
.
.
        </android.support.constraint.ConstraintLayout>
</layout>

You are reading a sample chapter from the Android Studio 3.2 Edition of this book.

Purchase the fully updated Android Studio 3.3 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format

Android Studio 3.3 Development Essentials - Android 9 Edition Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters and over 700 pages

Buy Print Preview Book

Once these changes have been made, switch back to Design mode and note that the new root view, though invisible in the layout canvas, is now listed in the component tree as shown in Figure 35-3:


As 3.2 data binding layout in tree.png


Build and run the app to verify that the addition of the layout element has not changed the user interface appearance in any way.

Adding the Data Element to Layout File

The next step in converting the layout file to a data binding layout file is to add the data element. For this example, the layout will be bound to MainViewModel so edit the main_fragment.xml file to add the data element as follows:

<?xml version="1.0" encoding="utf-8"?>
 
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
 
    <data>
        <variable
            name="myViewModel"
            type="com.ebookfrenzy.viewmodeldemo.ui.main.MainViewModel" />
    </data>
 
    <android.support.constraint.ConstraintLayout
        android:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.main.MainFragment">
.
.
</layout>

Build and run the app once again to make sure that these changes take effect.

Working with the Binding Class

The next step is to modify the code within the MainFragment.java file to obtain a reference to the binding class instance. This is best achieved by rewriting the onCreateView() method:

.
.
import android.databinding.DataBindingUtil;
import com.ebookfrenzy.viewmodeldemo.databinding.MainFragmentBinding;
.
public class MainFragment extends Fragment {
 
    private MainViewModel mViewModel;
 
    public MainFragmentBinding binding;
.
.
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, 
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
 
        binding = DataBindingUtil.inflate(
                inflater, R.layout.main_fragment, container, false);
 
        binding.setLifecycleOwner(this);
 
        return binding.getRoot();
    }
.
.
}

The old code simply inflated the main_fragment.xml layout file (in other words created the layout containing all of the view objects) and returned a reference to the root view (the top level layout container). The Data Binding Library contains a utility class which provides a special inflation method which, in addition to constructing the UI, also initializes and returns an instance of the layout‘s data binding class. The new code calls this method and stores a reference to the binding class instance in a variable:

binding = DataBindingUtil.inflate(
                inflater, R.layout.main_fragment, container, false);

The binding object will only need to remain in memory for as long as the fragment is present. To ensure that the instance is destroyed when the fragment goes away, the current fragment is declared as the lifecycle owner for the binding object.

binding.setLifecycleOwner(this);

Although the code for the onCreateView() method has been rewritten, the basic requirement that it return the root view of the layout has not changed. Fortunately, this can be obtained via a call to the getRoot() method of the binding object:

return binding.getRoot();

Assigning the ViewModel Instance to the Data Binding Variable

At this point, the data binding knows that it will be binding to an instance of a class of type MainViewModel but has not yet been connected to an actual MainViewModel object. This requires the additional step of assigning the MainViewModel instance used within the app to the viewModel variable declared in the layout file. Since the reference to the ViewModel is obtained in the onActivityCreated() method, it makes sense to make the assignment there:

.
.
import static com.ebookfrenzy.viewmodeldemo.BR.myViewModel;
.
.
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
 
    mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    binding.setVariable(myViewModel, mViewModel);
}

With these changes made, the next step is to begin inserting some binding expressions into the view elements of the data binding layout file.

Adding Binding Expressions

The first binding expression will bind the resultText TextView to the result value within the model view. Edit the main_fragment.xml file, locate the resultText element and modify the text property so that the element reads as follows:

<TextView
    android:id="@+id/resultText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text='@{safeUnbox(myViewModel.result) == 0.0 ? "Enter value" : String.valueOf(safeUnbox(myViewModel.result)) + " euros"}'
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

The expression begins by checking if the result value is currently zero and, if it is, displays a message instructing the user to enter a value. If the result is not zero, however, the value is converted to a string and concatenated with the word “euros” before being displayed to the user.

The result value only requires a one-way binding in that the layout does not ever need to update the value stored in the ViewModel. The dollarValue EditText view, on the other hand, needs to use two-way binding so that the data model can be updated with the latest value entered by the user, and to allow the current value to be redisplayed in the view in the event of a lifecycle event such as that triggered by a device rotation. The dollarText element should now be declared as follows:

<EditText
    android:id="@+id/dollarText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="96dp"
    android:ems="10"
    android:importantForAutofill="no"
    android:inputType="numberDecimal"
    android:text="@={myViewModel.dollarValue}"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Now that these initial binding expressions have been added a method now needs to be written to perform the conversion when the user clicks on the Button widget.

Adding the Conversion Method

When the Convert button is clicked, it is going to call a method on the ViewModel to perform the conversion calculation and place the euro value in the result LiveData variable. Add this method now within the MainViewModel.java file:

.
.
public class  MainViewModel extends ViewModel {
 
    private static final Float usd_to_eu_rate = 0.74F;
    public MutableLiveData<String> dollarValue = new MutableLiveData<>();
    public MutableLiveData<Float> result = new MutableLiveData<>();
 
    public void convertValue() {
        if ((dollarValue.getValue() != null) && 
                           (!dollarValue.getValue().equals(""))) {
            result.setValue(Float.valueOf(dollarValue.getValue()) 
                                                 * usd_to_eu_rate);
        } else {
            result.setValue(0F);
        }
    }
}

Note that in the absence of a valid dollar value, a zero value is assigned to the result LiveData variable. This ensures that the binding expression assigned to the resultText TextView displays the “Enter value” message if no value has been entered by the user.

Adding a Listener Binding

The final step before testing the project is to add a listener binding expression to the Button element within the layout file to call the convertValue() method when the button is clicked. Edit the main_fragment.xml file in text mode once again, locate the convertButton element and add an onClick entry as follows:

<Button
    android:id="@+id/convertButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="77dp"
    android:onClick="@{() -> myViewModel.convertValue()}"
    android:text="Convert"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/resultText" />

Testing the App

Compile and run the app and test that entering a value into the dollar field and clicking on the Convert button displays the correct result on the TextView (together with the “euros” suffix) and that the “Enter value” prompt appears if a conversion is attempted while the dollar field is empty. Also, verify that information displayed in the user interface is retained through a device rotation.

Summary

The primary goal of this chapter has been to work through the steps involved in setting up a project to use data binding and to demonstrate the use of one-way, two-way and listener binding expressions. The chapter also provided a practical example of how much code writing is saved by using data binding in conjunction with LiveData to connect the user interface views with the back-end data and logic of the app. In fact, 36 lines of code from the original app were replaced by just 12 lines when using data binding.


You are reading a sample chapter from the Android Studio 3.2 Edition of this book.

Purchase the fully updated Android Studio 3.3 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format

Android Studio 3.3 Development Essentials - Android 9 Edition Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters and over 700 pages

Buy Print Preview Book



PreviousTable of ContentsNext
An Overview of Android Jetpack Data BindingWorking with Android Jetpack Lifecycle-Aware Components