Changes

An Android Jetpack ViewModel Tutorial

185 bytes added, 18:23, 11 January 2019
no edit summary
 
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.
== About About the Project ==
In the chapter entitled [[Creating an Example Java Android App in Android Studio”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.
[[ImageFile:android_studio_view_model_activity_template.png]]
[[ImageFile:android_studio_view_model_container_area.png]]
[[ImageFile:android_studio_view_model_fragment.png]]
[[ImageFile:android_studio_view_model_ui.png]]
[[ImageFile:android_studio_layout_infer_constraints.png]]
</pre>
In the chapter entitled “Creating [[Creating an Example Java Android App in Android Studio”Studio]], the onClick property of the Button widget was used to designate the method to be called when the button is clicked by the user. Unfortunately, this property is only able to call methods on an Activity and cannot be used to call a method in a Fragment. To get around this limitation, we will need to add some code to the Fragment class to set up an onClick listener on the button. The code to do this can be added to the onActivityCreated() method of the MainFragment.java file as follows:
<pre>