Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.1 Development Essentials – Java Edition

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

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801815161
Pages 810 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (88) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Overview of Android View Binding 12. Understanding Android Application and Activity Lifecycles 13. Handling Android Activity State Changes 14. Android Activity State Changes by Example 15. Saving and Restoring the State of an Android Activity 16. Understanding Android Views, View Groups and Layouts 17. A Guide to the Android Studio Layout Editor Tool 18. A Guide to the Android ConstraintLayout 19. A Guide to using ConstraintLayout in Android Studio 20. Working with ConstraintLayout Chains and Ratios in Android Studio 21. An Android Studio Layout Editor ConstraintLayout Tutorial 22. Manual XML Layout Design in Android Studio 23. Managing Constraints using Constraint Sets 24. An Android ConstraintSet Tutorial 25. A Guide to using Apply Changes in Android Studio 26. An Overview and Example of Android Event Handling 27. Android Touch and Multi-touch Event Handling 28. Detecting Common Gestures using the Android Gesture Detector Class 29. Implementing Custom Gesture and Pinch Recognition on Android 30. An Introduction to Android Fragments 31. Using Fragments in Android Studio - An Example 32. Modern Android App Architecture with Jetpack 33. An Android Jetpack ViewModel Tutorial 34. An Android Jetpack LiveData Tutorial 35. An Overview of Android Jetpack Data Binding 36. An Android Jetpack Data Binding Tutorial 37. An Android ViewModel Saved State Tutorial 38. Working with Android Lifecycle-Aware Components 39. An Android Jetpack Lifecycle Awareness Tutorial 40. An Overview of the Navigation Architecture Component 41. An Android Jetpack Navigation Component Tutorial 42. Creating and Managing Overflow Menus on Android 43. An Introduction to MotionLayout 44. An Android MotionLayout Editor Tutorial 45. A MotionLayout KeyCycle Tutorial 46. Working with the Floating Action Button and Snackbar 47. Creating a Tabbed Interface using the TabLayout Component 48. Working with the RecyclerView and CardView Widgets 49. An Android RecyclerView and CardView Tutorial 50. A Layout Editor Sample Data Tutorial 51. Working with the AppBar and Collapsing Toolbar Layouts 52. An Android Studio Master/Detail Flow Tutorial 53. An Overview of Android Intents 54. Android Explicit Intents – A Worked Example 55. Android Implicit Intents – A Worked Example 56. Android Broadcast Intents and Broadcast Receivers 57. A Basic Overview of Threads and AsyncTasks 58. An Overview of Android Started and Bound Services 59. Implementing an Android Started Service – A Worked Example 60. Android Local Bound Services – A Worked Example 61. Android Remote Bound Services – A Worked Example 62. An Android Notifications Tutorial 63. An Android Direct Reply Notification Tutorial 64. Foldable Devices and Multi-Window Support 65. An Overview of Android SQLite Databases 66. The Android Room Persistence Library 67. An Android TableLayout and TableRow Tutorial 68. An Android Room Database and Repository Tutorial 69. Accessing Cloud Storage using the Android Storage Access Framework 70. An Android Storage Access Framework Example 71. Video Playback on Android using the VideoView and MediaController Classes 72. Android Picture-in-Picture Mode 73. An Android Picture-in-Picture Tutorial 74. Making Runtime Permission Requests in Android 75. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 76. Working with the Google Maps Android API in Android Studio 77. Printing with the Android Printing Framework 78. An Android HTML and Web Content Printing Example 79. A Guide to Android Custom Document Printing 80. An Introduction to Android App Links 81. An Android Studio App Links Tutorial 82. A Guide to the Android Studio Profiler 83. An Android Biometric Authentication Tutorial 84. Creating, Testing and Uploading an Android App Bundle 85. An Overview of Android Dynamic Feature Modules 86. An Android Studio Dynamic Feature Tutorial 87. An Overview of Gradle in Android Studio Index

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 2021 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}