Android Recyclerview Tutorial with SQLite ROOM : using MVVM, Dagger 2

What we will be building ?








A simple note taking app, which will have option to add notes and delete it. This will be a minimal design tutorial and hence we won't be spending much time on the app UI. This tutorial will be more focused on the MVVM, dagger2 and building an overall app architecture. This app will be improved in upcoming tutorials with more features, so make sure to stay tuned for that as well.

What are we will be covering ?

We will be using Java 8 to get access to various features like lambda functions, so we will need to enable this in app level build.gradle

We will be making use of data binding, so we will need to enable this also on your app level build.gradle

We will be using Dagger2 for building our dependencies

We will be having a base activity class which will be responsible for performing redundant operations like dependency injection, data binding, setting viewmodels for activities etc. So basically this app structure is developed with more activities to be incorporated in future.

The main reason for choosing MVVM and live data is that, with this pattern database operations like insert, delete gets effortlessly simple. We just need to observe to the database changes and as a result all the UI changes is reflected on the go. There are more advantages to this pattern, we will discuss these while moving forward.

Getting started with project building :

First of all, open your android studio, in file go to new>> new project and then create a project with empty activity

Dependencies Required ?

First of all update project level build.gradle as show below. Here we have set the versions for some dependencies that we will be using in our app :

Now go ahead and update your app level build.gradle with  dependencies for recyclerview,cardview,dagger,room,livedata etc as shown below :


As shown above we have enabled databinding by adding this

dataBinding {
enabled = true}

Also enable java 8 as shown below

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8}


Now let us jump into the coding session right away. Now, since we are making a notes app we will need to make a note model class. So in terms of SQLite ROOM, we will call this an entity. Entities in room are just another java class which is annotated with @Entity annotation. Annotating a class like this will help room in identifying it as an SQLite table. So now our room entity/table will have an notesId field which will be auto incremented on insertion, a notesTitle field and a notesDesc filed. We will be naming our table as notes_model which will be provided in brackets along with the @Entity annotation. So create a class like the following and name it NotesModel.java

Now go ahead and create a DAO class, by annotating it with @Dao. This class will basically act as an interface which will query the sqlite database as per our request. It will contain the various sql queries like insert,delete etc, now name it as NotesDao.java


Now it is time to create our database class, which should be annotated with @Database. Inside the annotation arguments, we can provide an array of entities where we can provide a list of tables/entities that we need inside our database, but for now we will be giving a single entity/table name which is NotesModel and we will keep the database version as 1 . So create the database class as follows :

It is now time to create our NotesRepository which will provide us with the live/updated database changes. It is where we define our live data methods from our db which will be later observed in activity. So create the repository as shown below and name it as NotesRepository.java

You might have noted the @Inject in the constructor which means that we will be getting these dependencies using dagger2, we will see how to create these dependencies using dagger2 later in this tutorial

Now create an abstract class BaseViewModel from which we will be extending all the viewmodel classes

Now we will need tocreate a viewmodel class for our MainActivity, so create MainActivityVM.java  like below

Now we will be creating the BaseActivity.java and make it abstract from which all our activties will be extending from. Also our BaseActivity.java will accept generic params for ViewDataBinding,BaseViewModel etc which means that the respective activities will be supplying our base activity with these params as required so that all databinding, setting viewmodels etc happens in the baseactivity itself.

We will also be using abstract methods for getting binding variable,activity layout, and viewmodel from respective activities. These abstract methods are getBindingVariable(),getLayoutId(),getViewModel() respectively.
now that we have all required attributes for databinding and dependency injection, we can create BaseActivity.java like following :


Now update your layout file which is present in res>> layout>>activity_main.xml , as shown below :

Now add a new layout file for the add new note dialog and name it custom_dialog_with_btns_view.xml


Now goto the project explorer on left hand side of your screen and right click on your package directory and create a new package named "di". This is to organize all your dagger files in this directory, it is optional to create a directory like this but it is highly recommended so that the code becomes more understandable.

Now right click on the di directory, and create a new abstract class and name it ActivityModule.java

In the above class you might have noticed the annotation @Module  which means that this class is a module and in this case this module will be used to provide various activities in our app like MainActivity. All the future generated activities must be defined here.

Now in the same directory - di, we will need the custom annotation ViewModelKey to generate our ViewModelModule.java . So first create interface ViewModelKey.java as follows

Now in the di directory, create another abstract class with @Module annotation and name it as ViewModelModule.java . This module class will provide all the ViewModels in the project. All the ViewModels should be defined here


Create another @Module annotated class AppModule.java which has included module as ViewModelModule.class as follows

Now you will need to design the view for note item, so go to res>>layout, right click on layout directory and click create new layout resource file and name it notes_item_view and add below contents to it

In the above layout for the recyclerview adapter, we have used data binding to set text into the textview. Basically, inorder to perform data binding, we need to make the root layout as "<layout>", also you will need to import the NotesModel and assign it to a variable as shown below.
<data>
<import type="com.example.recyclerviewsqliteroomcrud.persistance.NotesModel"/>
<variable
name="itemModel"
type="NotesModel" />
</data>
Now create a recyclerview adapter like shown below, also you will need to bind the above layout with this adapter in the viewholder

Now update your MainActivity.java  like show below



As shown above we have injected the MainActivityVM. Also we have returned the viewmodel(MainActivityVM) and layout file(activity_main) to the BaseActivity so that we can perform databinding and viewmodel setup inside the BaseActivity itself. This process will apply to all future activities that may be created in the app.
Now we will need to create a component class which will be used along with the earlier created module classes to generate the dependencies using dagger. So create AppComponent.java as shown below :


Now as a final step,we will need to generate the application class which will initialize dagger to build the necessary dependencies. So create BaseApplication.java

As soon as you copy the above file you may notice that DaggerAppComponent is given in red and shows error. This is because dagger has not yet generated the dependencies, inorder to do that click on File>>Sync project with gradle files . If everything goes well, the error will be gone and you may then organize the project structure as shown below(optional)


Finally, go to AndroidManifest.xml and update the application name as .BaseApplication as shown below





You may also checkout the below video tutorial which shows how and example with recyclerview,mvvm,dagger2,retrofit2

No comments:

Post a Comment