Android database connection using greenDAO library

greenDAO : Android ORM (Object/Relational Mapping) for SQLite database.

In Android, while dealing with big data projects we may require storing data locally. So very first thing comes in mind is SQLite.

But it may be complex to write SQL query for each transaction and it can be time-consuming.

Here is a simple solution to deal with android local database, greenDAO.

greenDAO is an object/relational mapping (ORM) tool for Android. It offers an object-oriented interface to the relational database SQLite.

Simple Guide:

Here are quick steps to start using greenDAO in our Android projects.

Add below dependencies into build.gradle(Module: app) file

apply plugin: 'org.greenrobot.greendao'

dependencies {

compile 'org.greenrobot:greendao-generator:3.2.0'
compile 'org.greenrobot:greendao:3.2.0'


And below code in build.gradle(Project: projectName) file

buildscript {
    repositories {
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'

Let’s create a class which will handle the database creation, say For better understanding, we will create a commonly used table, Users table.

public class DbMain {
    public static void main(String args[]) throws Exception {
        Schema schema = new Schema(1, 

        Entity users = schema.addEntity("Users");

        DaoGenerator daoGenerator = new DaoGenerator();
        daoGenerator.generateAll(schema, "./app/src/main/java");

Here, Schema class constructor has two parameters version and package_name. Whenever you change the database structure, add/delete/update table or table columns, you will need to increment the version by 1 and run this class.


How to create a table using greenDao?

Very simple, use Entity class, provide the table name in addEntity(table_name) method as a parameter, this will automatically create a table for you. Use the instance of it to add columns in the table. You can update it anytime, just remember to increment the version value by 1.

Entity users = schema.addEntity("Users");

The class not only creates a table but also it generates few more classes automatically.

  • This class has the operations for the overall database. It is Auto Generated by greenDao and don’t edit this class.
  • This class creates a session for each table. It is Auto Generated by greenDao and don’t edit this class.
  • For each table, there is a separate Dao class which will operate only on the table. It is Auto Generated by greenDao and don’t edit this class.
  • This is just a model class (POJO class), which helps to bind the data to operate on the table. It is Auto Generated by greenDao and don’t edit this class.


How to run the class?

Right click on class, click on Run “DbMain.main()” or simply press ctrl+shift+F10. By running this class means, recreating the data structure. Refer below screen shots for quick understanding.



Now, whenever you click on Run button in the toolbar, you might end up with running class each time. You will need to change Run Configuration to run your application.

Go to Run —> Edit Configurations —> from left panel select Android App —> app folder —> click on Ok. That’s it!



Now click on Run button, you will be able to run your project’s default configuration.

Till now we just created an environment to play and now it’s time to play!

CURD using greenDao

Create a data entry in a table.

 DaoSession daoSession = AppController.getInstance()
 UsersDao usersDao = daoSession.getUsersDao();
 Users user = new Users();
 usersDao.insert(user); //This will add a row in the Users table.

Update data entry in a table.

 DaoSession daoSession = AppController.getInstance().getDaoMaster().newSession();
 UsersDao usersDao = daoSession.getUsersDao();
     User> user = usersDao.queryBuilder()

     user.setName("Qice Technologies");
     usersDao.update(user); // this line will update the data

 } catch(Exception e) {
  //catch the exception, if there is no row available for the id.

Read the data from a table.

 DaoSession daoSession = AppController.getInstance()
 UsersDao usersDao = daoSession.getUsersDao();

 List<Users> users =  usersDao.queryBuilder().list(); 

 // This line gets all the row from the table, 
 //you can add  where clause to add constraints.

Delete data entry from a table.

DaoSession daoSession = AppController.getInstance().getDaoMaster().newSession();
 UsersDao usersDao = daoSession.getUsersDao();
 User> user = usersDao.queryBuilder()

 usersDao.delete(user); //this line will delete the data entry for the id.

 } catch(Exception e) {
    // catch the exception, if there is no row available for the id.

You can find a complete sample of the Android project using greenDao in our GitHub repository.


How to use Dagger 2 in Android

Dagger 2: One of the efficient dependency injection framework.

What is dependency injection?

Wiring classes together. That is one class is dependent on other is a dependency. Passing the object to the class rather than letting it create is Dependency Injection.

Why dependency injection?

It is good for testing. It makes code loosely coupled and easy to move anywhere across the application.

Why Dagger 2?

It is easy and efficient to use. Annotation based. An important aspect of Dagger 2 is that the library generates code for classes annotated with the @Component interface. You can use a class prefixed with Dagger. e.g. TestComponent interface can be used as DaggerTestComponent class. Dagger 2 relies purely on using Java annotation processors and compile-time checks to analyze and verify dependencies.

It is useful to avoid NullPointerException in activity/fragment/service over objects.

How to use dependency injection using Dagger 2?

Dagger 2 is an annotation based dependency injection framework, so everything is wrap up with annotation.

There are some annotations defined to use on different things like @Module annotation on class, @Component on an interface, @Provides on methods, @Inject on variables, parameters, constructors, etc.

Let’s have an example!

Very first thing we will require in our project to start is dependencies. So let’s put it in the build.gradle file of project’s app module.

dependencies {
    //dagger2 dependecies
    compile ""
    annotationProcessor ""
    provided 'javax.annotation:jsr250-api:1.0'

    //Retrofit dependencies useful to do network calls
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'

@Module: It signals to Dagger to search within the available methods for possible instance providers.

Now, create a class say,

public class AppModule {
    Application application;

    public AppModule(Application application){
        this.application = application;

    Application provideApplication(){
        return application;


We will create one more class say

public class NetModule {

    String mBaseUrl;

    // Constructor needs one parameter to instantiate.
    public NetModule(String baseUrl) {
        this.mBaseUrl = baseUrl;
    //Remember, Dagger will only look for methods annotated with
    // Application reference must come from AppModule.class
    SharedPreferences providesSharedPreferences(Application 
                                        application) {
        return PreferenceManager

    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        return gsonBuilder.create();

    Retrofit provideRetrofit(@NonNull Gson gson) {
        Retrofit retrofit = new Retrofit.Builder()
        return retrofit;

Now you might get clear idea that what will be the use of the first module. AppModule class provides the Application object which will useful in NetModule class in a provideSharedPreference() method as a parameter.

@Provides: It denotes to Dagger that the method defined just below to the @Provides annotation is the constructor for the return type. In a method with @Provides annotation, all the parameters should come from outside no matter how many parameters you will require. This method will return the object based on Scope.

@Singleton: It is the scope for the objects returned by the method. @Singleton annotation signals to the Dagger compiler that the instance should be created only once in the application.

@Component: Now let’s see how to use @Component annotation,

@Component (modules = {AppModule.class, NetModule.class})
public interface NetComponent {

    void inject(MainActivity activity);
    /* Create different inject() method for different         
    activities/fragent/service */
    void inject(MyFragment fragment);
    void inject(MyService service);


This is nothing but an interface annotated with @Component. It assigns references in our activities, services, or fragments to have access to singletons we earlier defined.

Note that the activities, services, or fragments that can be added should be declared in this interface with individual inject() methods. We can name the method something else but it is recommended to use as it is.

Next step is, build the component. We should do all this work within a Application class since these instances should be declared only once throughout the entire lifespan of the application, remember we have given the Singleton scope.

public class MyApp extends Application {
   private final String TAG = getClass().getSimpleName();
   private static NetComponent netComponent;
    public void onCreate() {
         /*Add all the list of modules that are part of the 
           component here */
         netComponent = DaggerNetComponent.builder()
                .appModule(new AppModule(this))
                .netModule(new NetModule(""))

        Log.e(TAG, "onCreate: netComponent = "+netComponent );

    public static NetComponent getNetComponent() {
        return netComponent;

DaggerNetComponent is an auto-generated class, Dagger will generate it at compile time.

If a Dagger 2 component does not have any constructor arguments for any of its modules, we can use .create() as a shortcut instead:

netComponent = DaggerNetComponent.create();

How to get the object in Activity/Fragment?

Here is a class which will call to the Dagger component and gets the injected objects.

public class MainActivity extends AppCompatActivity {
    SharedPreferences sharedPreferences;
    private final String TAG = getClass().getSimpleName();

    InjectConstructor injectConstructor;

    Retrofit retrofit;

    protected void onCreate(Bundle savedInstanceState) {


        // Here we will get all the injected class's objects here
        Log.e(TAG, "onCreate: sharedPreferences = 
                   "+sharedPreferences );
        Log.e(TAG, "onCreate: injectConstructor = 
                   "+injectConstructor );
        Log.e(TAG, "onCreate: retrofit = "+retrofit );

        /* We are getting InjectConstructor class object without 
         calling its constructor with new keyword and can 
         access its methods too. */



Note that Dagger does not support injection into private fields.

public class InjectConstructor {
    private final String TAG = getClass().getSimpleName();

    public InjectConstructor (){
        Log.e(TAG, "InjectConstructor: Inside of Constructor");

    public void testIt(){
        Log.e(TAG, "testIt: Inside a method of 

If you see, InjectConstructor class is used in above MainAcitivity. What is it? A simple class whose constructor is annotated with @Inject annotation.

If you want to create an instance of a class without calling its constructor with a new keyword, you can just add @Inject annotation above the class’s constructor. Doing this Dagger gets a signal that needs to create an instance for the class, it will create automatically.  You need to add @Inject annotation over the class object declaration while using it in Activity/Fragment/any other classes.


Android network call using Retrofit library

Retrofit : A type-safe HTTP client for Android and Java.

Nowadays, a Smart phone becoming a trend. And hence the scope of Android is increasing continuously. But we also need security while transferring our data on the network. So here is a type-safe library which takes care of the security while making network calls in Android programming.

Retrofit is used to make network calls (REST). This is an annotation based library by Square.

It reduces the long code and makes server calls in few lines of code, which also reduces the time and efforts of a developer.

There are five built-in annotations in Retrofit GET, POST, PUT, DELETE, and HEAD. We will see few of them in brief later.

 Let’s see a sample first

Very first thing, add below dependencies in your project build.gradle(Module: app) file,

compile ''
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

Second, add an internet permission in AndroidManifest.xml file because we are dealing with network,

<uses-permission android:name="android.permission.INTERNET"/>

Now, Create a new class to create an instance of Retrofit with base Url of your backend API.

public class ApiClient implements Constant {
private static Retrofit retrofit = null;

public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
return retrofit;

Next, create an interface which will have an actual call to the server, let’s called it

public interface ApiInterface {
  @GET("endpoint/user/get_all/")  //this is the rest api url
   Call<Response> getAllUsers(@Query("api_key") String apiValue);

    /* You can also specify query parameters in the URL.
      The response of above and this below query will be same. */
    Call<RegionResponse> getAllUsers();



Next, create another class, which will hold the response returned by the API.
Here, @SerializedName(“response”) is a key of the response object.

public class Response {

private ArrayList<ResponseModel> results;

public ArrayList<ResponseModel> getResults() {
return results;
public void setResults(ArrayList<ResponseModel> results) {
this.results = results;

Create a model class(pojo class) to hold the response for each object. @SerializedName holds the key of the field.

public class ResponseModel {

private String id;
private String name;
private String imageUrl;

public ResponseModel (String id, String name, String imageUrl){
super(); = id; = name;
this.imageUrl = imageUrl;


public String getId(){
return id;
public void setId(String id){ = id;
public String getImageUrl(){
return imageUrl;
public void setImageUrl(String imageUrl){
this.imageUrl = imageUrl;
public String getName(){
return name;
public void setName(String name){ = name;


Now finally, lets make a call from the activity. Let’s create it!

public class MainActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
// Create instance of get Retrofit instance and connect with the network call methods.
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

// Make a call to specific server API
Call<ResponseObject> call = apiService.getAllUsers(API_KEY);
call.enqueue(new Callback<ResponseObject>() {
public void onResponse(Call<ResponseObject> call, retrofit2.Response<ResponseObject> response) {
// Here you will get the response.
int statusCode = response.code();
ArrayList<ResponseModel> responseModel = response.body().getResults();
Log.e(TAG, "onResponse: statusCode = "+statusCode+" responseModel = "+responseModel);
// Now you can set your adapter for RecyclerView etc...

public void onFailure(Call<com.ilandmusic.retrofit.Response> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());

Give a try to above code and I hope you will be able to make the first request of server API using the Retrofit library!


Understand use of Retrofit

Retrofit supports
* query parameter support
* Object conversion to request body (e.g., JSON, protocol buffers)
* Multipart request body and file upload

Built-in annotations :

GET Method
Lets see how we can get list of all users just by writing couple of lines.

Call<Response> getAllUsers(@Query("api_key") String apiValue);

You can also specify query parameters in the URL. The response of above and this below query will be same.

Call<Response> getAllUsers();

Also can specify the path, as shown below example,

Call<Response> getUserDetails(@Path("id") int id, @Query("api_key") String apiValue);

You can send headers by defining @Headers annotation on request call method or as a parameter to the request call method with @Header annotation. Below example explain itself.

"api_key: Api-value",
"token: Tokan-value"
Call<Response> getUserDetails(@Path("id") int id);

POST Method
An object can be specified for use as an HTTP request body with the @Body annotation. Below example shows how we can make a POST server call,

Call<User> createUser(@Body User user);

If you are using converter on Retrofit instance, the object user will be converted using it. If no converter is added, only RequestBody can be used as a object. Above query can be,

Call<User> createUser(@Body RequestBody user);

If you want to send sensitive data but without @Body, like user details over a network, no worries, Retrofit has the @FormUrlEncoded annotation. @FormUrlEncoded this will encode the data in form of key-value pair which will be annotated with @Field containing the name and the object providing the value.

Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

PUT Method
You can send Multipart requests by using @Multipart annotation on the request call method. Parts are declared using the @Part annotation.

Call<User> updateUser(@Part("image") RequestBody image, @Part("description") RequestBody description);