Repository
https://github.com/googlesamples/android-architecture-components/
What Will I Learn?
- How to Implement ViewModel of the Android Architecture Component
- How to create a ToDo Listing Application .
Requirements
- IDE for developing android applications(Android Studio or IntelliJ)
- An Android Emulator or device for testing
- Java Programming knowledge
- Must have read the Part 1 , 2 & 3 of this series
Other Resource Materials
Difficulty
- Intermediate
Tutorial Duration 20- 25 Minutes
TUTORIAL CONTENT
In this Tutorial, we are going to continue learning the Android Architecture Components, specifically the ViewModel component. But before we proceed to today's tutorial, below is a brief highlight of the former parts of this tutorial series.
PART 1 : In the part one of this tutorial series, we implemented the Room Database component of the Android Architecture Components in creating a simple todo application. Here we carried the following operations: Insert new Task Entry and load all task from data base.
PART 2 : In the second part of this series, we learned the Singleton Pattern and implemented it with the Executor. The Executor here, enabled us to make database queries on a separate thread other than the Main Thread.
PART 3 : In the third part of this tutorial series, we learn about the LiveData of the android architecture components and how to implement it in our to-do list application. The LiveData as we saw from our last tutorial notifies our UI of data change on the database. With this , we do not have to re query our database every time a change is made to the Database.
For this PART 4 of the series, we will learn about ViewModel and how to implement it in our to-do list application. OK lets get started!!!
STEP 1 : Update Gradle Files
You have to add the component libraries to your gradle files. Add the following code to your build.gradle (Module: app) file, below the dependencies block.
implementation "android.arch.lifecycle:extensions:1.1.0"
annotationProcessor "android.arch.lifecycle:compiler:1.1.0"
STEP 2 : Create a ViewModel Class MainScreenViewModel that Extends AndroidViewModel
What is a ViewModel?
According to the android architecture component documentation, the ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
Lifecycle of a ViewModel
the
The figure above shows the lifecycle of the ViewModel. Basically the ViewModel object is created when the activity is first created. The viewModel created persist even when activity is rotated and its onCreate method called, The ViewModel calls its onCleared method when the activity is destroyed, to release memory resources.
Why ViewModel?
In our to-do list application, when we rotate the android device, there is a configuration change (Screen orientation change). our activity is destroyed and recreated thus querying our Database every time this change occurs . Without the ViewModel, our application keeps querying the database for data every time onCreate on the main activity is called. The image below shows our application rotated several times without the ViewModel. The log message says reading from Database every time. This is not efficient at all.
Also Caching large data (our list of task) is made easy with ViewModel.
code block for class MainScreenViewModel
public class MainScreenViewModel extends AndroidViewModel {
private LiveData<List<Task>> taskList;
public MainScreenViewModel(@NonNull Application application) {
super(application);
AppDataBase appDataBase = AppDataBase.getsInstance(this.getApplication());
Log.i("View Model"," Retrieving data from database");
taskList = appDataBase.taskDao().loadAllTask();
}
public LiveData<List<Task>> getTaskList() {
return taskList;
}
}
Code Explanation
- Basically we created a class MainScreenViewModel that extends AndroidViewModel.
- AndroidViewModel is a ViewModel that accepts an Application parameter in its constructor
- Were created our livedata object taskList to store the list of tasks retrieved from the database
- The database object is declared and initialized in the constructor .
- The taskList variable is initialized in the constructor by calling the loadAllTask method in taskDoa on the database object.
- we create a getter method getTaskList that returns a list of tasks wrapped in a liveData object
STEP 3 : Update Code in getTasks Method
Current Code in getTask method of MainActivity
private void getTasks() {
final LiveData<List<Task>> tasks = appDataBase.taskDao().loadAllTask();
tasks.getTaskList().observe(MainActivity.this, new Observer<List<Task>>() {
@Override
public void onChanged(@Nullable List<Task> tasks) {
toDoListAdapter.setTasks(tasks);
}
});
}
Code Explanation
- in this block of code , we retrieve our list of task from the database and then observe it for any change in the database. This is made possible by the Livedata
- This method is called every time our activity is rotated so our database is queried again.
New Code in getTask method of MainActivity
private void getTasks() {
MainScreenViewModel viewModel = ViewModelProviders.of(this).get(MainScreenViewModel.class);
viewModel.getTaskList().observe(MainActivity.this, new Observer<List<Task>>() {
@Override
public void onChanged(@Nullable List<Task> tasks) {
toDoListAdapter.setTasks(tasks);
}
});
}
Code Explanation
- Here we get our ViewModel by calling the providers class of this activity, and pass the view model class as a parameter.
- Now, we retrieve our live data object using the getTasklist method from the ViewModel.
- Now if we rotate our device, there are no new calls to the database as our live data is cached in the ViewModel.
STEP 4 : Test the App
After refactoring our codes to implement ViewModel, we can now proceed to test the app. Below is the app demo.
The image below shows messages from the logcat . The query to our database is done just once even after multiple rotation
Curriculum
- Creating a ToDoList Android Application with Android Architecture Components - PART 1
- Creating a ToDoList Android Application with Android Architecture Components - PART 2
- Creating a ToDoList Android Application with Android Architecture Components - PART 3
Proof of Work Done
The complete source code can be found on github
https://github.com/enyason/TodoApp_Android_Architecture_Components
Yet another very Informative tutorial, I liked the way you explained basic concepts in detail through out the series so far. While I think a Todo app is a good example to learn Android, I will suggest you to take more challenging and creative examples and more number of open source libraries in your advanced tutorial series.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
thanks @aneilpatel for the suggestion
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thanks for the contribution.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thanks @deathwing for evaluating my contribution. I'll see to your advice and address it in my next contributions .
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hey @ideba
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit