Dedicated Server
Showing posts with label recyclerview. Show all posts
Showing posts with label recyclerview. Show all posts

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

Loading images using picasso library in android

In this tutorial we are about to load image in recyclerview using picasso library as shown in the following gif
images loaded in recyclerview using picasso library

In this tutorial we will be parsing the following json array example into a recyclerview along with the images
You can check the json file here https://navneet7k.github.io/cars_list.json
Update internet permission in AndroidManifest.xml as shown below
Add the dependencies for cardview,design,retrofit,converter-gson and picasso in your app level build.gradle as shown below
Please make sure that you add the dependencies in app level build.gradle itself and not project level build.gradle like depicted below

build.gradle files


Create model class like shown below

CarItem.java
Create recyclerview adapter

DataAdapter.java
Here we have used

 Picasso.get().load(articles.get(i).getImage()).resize(500,500).into(viewHolder.car_img); 

to load the image into car_img using Picasso library. Also I have implemented a filter method in the above adapter class which you can use to integrate a search feature in the above recyclerview - you may check this tutorial to integrate search feature inside recyclerview.

create activity file

MainActivity.java
Since we have to parse a json array example, we have used List<CarItem> as response parameter type in retrofit callback methods as shown above. If we were parsing a json object example, we would have to set CarItem as response parameter type.

RequestInterface.java
Now create the resource files

activity_main.xml
item_layout.xml
colors.xml
strings.xml

Android RecyclerView search using adapter Filter method

The following is an overview of what we are about to learn in this tutorial

RecyclerView SearchView example
In this tutorial, we will be parsing a json array example into  a recyclerview as shown above and then use the filter feature in recyclerview adapter to perform search operations in the recyclerview list. The below json is the one that we are about to parse.





AndroidManifest.xml
app level build.gradle file
First of all, add the following changes in resource files

strings.xml
colors.xml
Now go to your "res" dirctory and right click on it, go to new>>Android Resource Directory and choose resource type as menu. Then click ok to create menu directory inside res folder. Now create another file menu_main.xml inside the menu directory that we just created.

menu_main.xml
Now make the following changes and additions to the layout files

activity_main.xml
The following layout provides the design for each item in a recyclerview

item_layout.xml
Our res folder will have the below directory structure
res folder directory structure

Now let us head over to some java code, first of all go ahead and create your model class like shown below
CarModel.java.java

Now create a recyclerview adapter for your recyclerview like shown below
DataAdapter.java
Now create a retrofit interface to define your network endpoint like shown below
RequestInterface.java
Since we are parsing json array example, we will need to fetch the results as a list of CarModel. So finally create MainActivity.java file with the network calls as shown below
Now the complete directory structure will be like
full directory structure

RecyclerView with sqlite database android tutorial

The following gif is an overview of what we are about to build
add, edit, delete, search contacts




First of all create a new project in android studio
now setup the following dependencies in your app level build.gradle file

implementation 'com.android.support:appcompat-v7:28.0.0' 
implementation 'com.android.support:design:28.0.0' 
implementation 'com.android.support:recyclerview-v7:28.0.0' 
implementation 'com.android.support:cardview-v7:28.0.0'

Now setup all the assets like shown below

go to res >> drawable and create brown_border.xml,pedit.png,pdelete.png

brown_border.xml

pedit.png(download)


pdelete.png(download)


Now go to res >> values >> colors.xml and add the following

Now go to res >> values >> strings.xml and add the following

Now create res >> menu >> menu_main.xml like this

Now create res >> layout and add the following

activity_main.xml add_contact_layout.xml contact_list_layout.xml
Now let us look into some java code
First of all create a helper class which extends SQLiteOpenHelper as shown below

SqliteDatabase.java
The above helper class provides methods to perform all the basic CRUD operations like add, update, delete etc.Now we should create a model class for the contacts object, it should be like

Contacts.java
Now we should create a recyclerview adapter for our recyclerview. It will include a Filter method which would be used to do search operations within our contacts list.

ContactAdapter.java

Below is the code for ContactViewHolder.java which is used in the above adapter class
Update your MainActivity.java file like shown below
With this, we have come to the end of this tutorial, now try running the app!

You may also check an advanced tutorial here >>
Android Recyclerview Tutorial with SQLite ROOM : using MVVM, Dagger 2