In this blog, we will learn about using Android Room, LiveData And View Model from the Android Architecture Components.
Why do I need to know about these?
Well, this makes Android development easy and fast.
What exactly is Android Architecture Components?
A new collection of libraries that help you design robust, testable, and maintainable apps. — developer.android.com
How does this help me as a developer?
It helps us address two pain points:
- Manage our UI components lifecycle
- Persist data over configuration changes
Ok, wanna read more, let’s get started :
We will cover three major parts of the Android Architecture Components Library.
- Room
- ViewModel
- LiveData
ROOM
Android Room is a library that helps you in easily accessing the database. You can define your database by adding annotations in your Model class. Now you can query your data without having to deal with cursors or loaders.
If you have no knowledge about the android room, then you should read this article:
If you have some knowledge about the android room and are having some difficulties still in using, you should read this article :
View Model
The
ViewModel
class is designed to store and manage UI-related data in a lifecycle conscious way. TheViewModel
class allows data to survive configuration changes such as screen rotations. — developer.android.com
What this means is that ViewModel class can retain its state/data even during an orientation change.
ViewModels do not contain code related to the UI. This helps in the decoupling of our app components.
In Room, the database instance should ideally be contained in a ViewModel rather than on the Activity/Fragment.
Creating an Android ViewModel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class MyViewModel extends AndroidViewModel { private final LiveData<List<MyObject>> currentList; private AppDataBase appDataBase; public MyViewModel(@NonNull Application application) { super(application); appDataBase = AppDataBase.getInstance(application.getApplicationContext()); currentList = appDataBase.myDao().getAll(); } public LiveData<List<MyObject>> getCurrentData(){ return currentList; } } |
Every ViewModel class must extend the ViewModel class. If your ViewModel needs the application context, it must extend AndroidViewModel. The ViewModel will contain all the data needed for our Activity.
Using this ViewModel and observing changes in activity/fragment.
All you need to do is activate your ViewModel Instance after your activity/fragment has been created. You can do this for activity by initializing the View Model Instance in onCreate Method of your activity or onActivityCreatedmethod of your fragment.
For Fragment something like this needs to be done :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class MyFragment extends Fragment{ private MyViewModel mMyViewModel; // field in your activity. @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { mMyViewModel = ViewModelProviders.of(this).get(MyViewModel.class); mMyViewModel.getCurrentData().observe(this, new Observer<List<MyObject>>() { @Override public void onChanged(@Nullable List<MyObject> currentList) { // do whatever you want to do here } }); } } |
For Activity something like this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class MainActivity extends AppCompatActivity { private MyViewModel mViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mViewModel = ViewModelProviders.of(this).get(MyViewModel.class); mViewModel.getCurrentData().observe(MainActivity.this, new Observer<List<MyObject>>() { @Override public void onChanged(@Nullable List<MyObject> currentList) { //do whatever you need to do here } }); |
NOTE:
Whenever we need to use ViewModels inside our Activity, the Activity must extend LifecycleActivity.
LiveData
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state. — developer.android.com
What do we need to change for using live data in our current Android Project?
I have used only these :
1 2 3 4 5 6 7 8 9 |
// ViewModel and LiveData implementation "android.arch.lifecycle:extensions:1.0.0" annotationProcessor "android.arch.lifecycle:compiler:1.0.0" kapt "android.arch.lifecycle:compiler:1.0.0" // Room implementation "android.arch.persistence.room:runtime:1.0.0" annotationProcessor "android.arch.persistence.room:compiler:1.0.0" kapt "android.arch.persistence.room:compiler:1.0.0" |
You can find the whole list of dependencies over here :
https://developer.android.com/topic/libraries/architecture/adding-components.html
Changes in your Dao class.
1 2 3 4 5 6 7 8 |
@Dao public interface MyDao { // your other dao related methods @Query("SELECT * FROM table") LiveData<List<MyObject>> getAll(); } |
Hope This helps you, Keep coding and keep sharing 🙂
Reference : https://android.jlelse.eu/android-architecture-components-room-livedata-and-viewmodel-fca5da39e26b