Reader small image

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

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

36. An Android Jetpack Data Binding Tutorial

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.

36.1 Removing the Redundant Code

If you have not already done so, copy the ViewModelDemo project folder and save it as ViewModelDemo_LiveData so that it can be used again in the next chapter. Once copied, open the original ViewModelDemo project ready to implement data binding.

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 androidx.lifecycle.ViewModelProvider;

 

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...

36.2 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: ViewModelDemo.app)) as highlighted in Figure 36-1:

Figure 36-1

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

plugins {

    id 'com.android.application'

}

  

android {

  

    buildFeatures {

        dataBinding = true

    }

    compileSdkVersion 29

.

.

}

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:

Figure 36-2

...

36.3 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 Code 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">

 

        <androidx.constraintlayout.widget.ConstraintLayout

            android:id="@+id/main...

36.4 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" />

  ...

36.5 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 androidx.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,

           ...

36.6 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 = new ViewModelProvider(this).get(MainViewModel.class);

    binding.setVariable(myViewModel, mViewModel);

}

If Android Studio reports myViewModel as undefined...

36.7 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="...

36.8 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(""...

36.9 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 Code 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...

36.10 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.

36.11 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.

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 2021Publisher: PacktISBN-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.
undefined
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 £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth