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

34. An Android Jetpack LiveData Tutorial

The previous chapter began the process of designing an app to conform to the recommended Jetpack architecture guidelines. These initial steps involved the selection of the Fragment+ViewModel project template and the implementation of the data model for the app user interface within a ViewModel instance.

This chapter will further enhance the app design by making use of the LiveData architecture component. Once LiveData support has been added to the project in this chapter, the next chapters (starting with “An Overview of Android Jetpack Data Binding”) will make use of the Jetpack Data Binding library to eliminate even more code from the project.

34.1 LiveData - A Recap

LiveData was introduced previously in the chapter entitled “Modern Android App Architecture with Jetpack”. As described earlier, the LiveData component can be used as a wrapper around data values within a view model. Once contained in a LiveData instance, those variables become observable to other objects within the app, typically UI controllers such as Activities and Fragments. This allows the UI controller to receive a notification whenever the underlying LiveData value changes. An observer is set up by creating an instance of the Observer class and defining an onChange() method to be called when the LiveData value changes. Once the Observer instance has been created, it is attached to the LiveData object via a call to the LiveData object’s observe() method.

LiveData instances can be declared as being mutable using the MutableLiveData class, allowing both the ViewModel and UI controller to make changes to the underlying data value.

...

34.2 Adding LiveData to the ViewModel

Launch Android Studio, open the ViewModelDemo project created in the previous chapter and edit the MainViewModel.java file which should currently read as follows:

package com.ebookfrenzy.viewmodeldemo.ui.main;

 

import androidx.lifecycle.ViewModel;

 

public class MainViewModel extends ViewModel {

 

    private static final Float usd_to_eu_rate = 0.74F;

    private String dollarText = "";

    private Float result = 0F;

 

    public void setAmount(String value) {

        this.dollarText = value;

        result = Float.valueOf(dollarText)*usd_to_eu_rate;

    }

 

    public Float getResult()

    {

        ...

34.3 Implementing the Observer

Now that the conversion result is contained within a LiveData instance, the next step is to configure an observer within the UI controller which, in this example, is the MainFragment class. Locate the MainFragment.java class (app -> java -> <package name> -> MainFragment), double-click on it to load it into the editor and modify the onActivityCreated() method to create a new Observer instance named resultObserver:

package com.ebookfrenzy.viewmodeldemo.ui.main;

 

import androidx.lifecycle.Observer;

.

.

@Override

public void onActivityCreated(@Nullable Bundle savedInstanceState) {

.

.

    dollarText = getView().findViewById(R.id.dollarText);

    resultText = getView().findViewById(R.id.resultText);

    convertButton = getView().findViewById(R.id.convertButton);

 

    resultText.setText(mViewModel.getResult()...

34.4 Summary

This chapter demonstrated the use of the Android LiveData component to make sure that the data displayed to the user always matches that stored in the ViewModel. This relatively simple process consisted of wrapping a ViewModel data value within a LiveData object and setting up an observer within the UI controller subscribed to the LiveData value. Each time the LiveData value changes, the observer is notified and the onChanged() method called and passed the updated value.

Adding LiveData support to the project has gone some way towards simplifying the design of the project. Additional and significant improvements are also possible by making use of the Data Binding Library, details of which will be covered in a later chapter. Before doing that, however, we will look saving ViewModel state.

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