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

33. An Android Jetpack ViewModel Tutorial

The previous chapter introduced the key concepts of Android Jetpack and outlined the basics of modern Android app architecture. Jetpack essentially defines a set of recommendations describing how an Android app project should be structured while providing a set of libraries and components that make it easier to conform with these guidelines with the goal of developing reliable apps with less coding and fewer errors.

To help re-enforce and clarify the information provided in the previous chapter, this chapter will step through the creation of an example app project that makes use of the ViewModel component. This example will be further enhanced in the next chapter with the inclusion of LiveData and data binding support.

33.1 About the Project

In the chapter entitled “Creating an Example Android App in Android Studio”, a project named AndroidSample was created in which all of the code for the app was bundled into the main Activity class file. In the chapter that followed, an AVD emulator was created and used to run the app. While the app was running, we experienced first-hand the kind of problems that occur when developing apps in this way when the data displayed on a TextView widget was lost during a device rotation.

This chapter will implement the same currency converter app, this time using the ViewModel component and following the Google app architecture guidelines to avoid Activity lifecycle complications.

33.2 Creating the ViewModel Example Project

The first step in this exercise is to create the new project. Begin by launching Android Studio and, if necessary, closing any currently open projects using the File -> Close Project menu option so that the Welcome screen appears.

When the AndroidSample project was created, the Empty Activity template was chosen as the basis for the project. For this project, however, the Fragment + ViewModel template will be used. This will generate an Android Studio project structured to conform to the architectural guidelines.

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Fragment + ViewModel template before clicking on the Next button.

Enter ViewModelDemo into the Name field and specify com.ebookfrenzy.viewmodeldemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language...

33.3 Designing the Fragment Layout

The next step is to design the layout of the fragment. Locate the main_fragment.xml file in the Project tool window and double click on it to load it into the layout editor. Once the layout has loaded, select the existing TextView widget and use the Attributes tool window to change the id property to resultText.

Drag a Number (Decimal) view from the palette and position it above the existing TextView. With the view selected in the layout refer to the Attributes tool window and change the id to dollarText.

Drag a Button widget onto the layout so that it is positioned below the TextView, and change the text attribute to read “Convert”. With the button still selected, change the id property to convertButton. At this point, the layout should resemble that illustrated in Figure 33-3:

Figure 33-3

Click on the Infer constraints button (Figure 33-4) to add any missing layout constraints:

Figure 33-4

Finally, click on...

33.4 Implementing the View Model

With the user interface layout completed, the data model for the app needs to be created within the view model. Within the Project tool window, locate the MainViewModel.java file, double-click on it to load it into the code editor and modify the class so that it reads 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.parseFloat(dollarText)*usd_to_eu_rate;

    }

 

  ...

33.5 Associating the Fragment with the View Model

Clearly, there needs to be some way for the fragment to obtain a reference to the ViewModel in order to be able to access the model and observe data changes. A Fragment or Activity maintains references to the ViewModels on which it relies for data using an instance of the ViewModelProvider class.

A ViewModelProvider instance is created using the ViewModelProvider class from within the Fragment. When called, the class initializer is passed a reference to the current Fragment or Activity and returns a ViewModelProvider instance as follows:

ViewModelProvider viewModelProvider = new ViewModelProvider(this);

Once the ViewModelProvider instance has been created, the get() method can be called on that instance passing through the class of specific ViewModel that is required. The provider will then either create a new instance of that ViewModel class, or return an existing instance:

ViewModel viewModel = viewModelProvider.get(MainViewModel...

33.6 Modifying the Fragment

The fragment class now needs to be updated to react to button clicks and to interact with the data values stored in the ViewModel. The class will also need references to the three views in the user interface layout to react to button clicks, extract the current dollar value and to display the converted currency amount. With the MainFragment class file loaded into the code editor, modify the onActivityCreated() method to obtain and store references to the three view objects as follows:

.

.

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

 

import com.ebookfrenzy.viewmodeldemo.R;

 

public class MainFragment extends Fragment {

 

    private MainViewModel mViewModel;

    private EditText dollarText;

    private TextView resultText;

    private Button convertButton;

.

.

...

33.7 Accessing the ViewModel Data

When the button is clicked, the onClick() method needs to read the current value from the EditText view, confirm that the field is not empty and then call the setAmount() method of the ViewModel instance. The method will then need to call the ViewModel’s getResult() method and display the converted value on the TextView widget.

Since LiveData is not yet being used in the project, it will also be necessary to get the latest result value from the ViewModel each time the Fragment is created.

Remaining in the MainFragment.java file, implement these requirements as follows in the onActivityCreated() method:

@Override

public void onActivityCreated(@Nullable Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    mViewModel = new ViewModelProvider(this).get(MainViewModel.class);

 

 

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

33.8 Testing the Project

With this phase of the project development completed, build and run the app on the simulator or a physical device, enter a dollar value and click on the Convert button. The converted amount should appear on the TextView indicating that the UI controller and ViewModel re-structuring appears to be working as expected.

When the original AndroidSample app was run, rotating the device caused the value displayed on the resultText TextView widget to be lost. Repeat this test now with the ViewModelDemo app and note that the current euro value is retained after the rotation. This is because the ViewModel remained in memory as the Fragment was destroyed and recreated and code was added to the onActivityCreated() method to update the TextView with the result data value from the ViewModel each time the Fragment re-started.

While this is an improvement on the original AndroidSample app, there is much more that can be achieved to simplify the project by making use...

33.9 Summary

In this chapter we revisited the AndroidSample project created earlier in the book and created a new version of the project structured to comply with the Android Jetpack architectural guidelines. The chapter outlined the structure of the Fragment + ViewModel project template and explained the concept of basing an app on a single Activity using Fragments to present different screens within a single Activity layout. The example project also demonstrated the use of ViewModels to separate data handling from user interface related code. Finally, the chapter showed how the ViewModel approach avoids some of the problems of handling Fragment and Activity lifecycles.

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