Tutorial: How to easily integrate greenDAO into your Android project

[UPDATE: 20.12.2016]

This tutorial demonstrates greenDAO 2.x integration. Since greenDAO 3.x was released, its integration differs from 2.x. Now, you can either have a generation project or everything in one app's project. There is a build-in encryption (SQLCipher underneath) which you can use if you want. There are now annotations and the package name has been changed to org.greenrobot.greendao. Here is a good article if you want to migrate to greenDAO 3.x - Updating to greenDAO 3 and annotations and here are some Code examples.


Hi, guys!

Today I want to present you my new tutorial about greenDAO integration. For those who haven't heard, this is a great open source Android ORM solution which enables you to forget about SQLite low-level stuff and concentrate on the database's overall lifecycle, models and how do they relate. You don't actually need to bother how to populate the database and how the relations work, because greenDAO handles it for you. All you need to know is what you want to keep in your DB.

Sounds great, huh? But what about performance? You see, greenDAO is a bit different from other ORMs, - it doesn't use annotations and so it got rid from expensive data parsing and reflection (which is awfully slow), but instead you generate what you need, and then - make use of it. This makes greenDAO really fast.There are two main modules: core and generator. Only the first one is packed into your app and the second is only used for class generation (you won't need or use it directly in your app). This is definitely something that makes greenDAO so special, but at the same time, the first-time configuration seems a bit ambiguous. And so today I want to help those of you who have to deal with it for the first time. We will use Android Studio and its standard means for that purpose.

Lets begin! First of all, create a new Android Project, with the following settings:

  • Application name: GreenDAOExample
  • Package name: com.abc.greendaoexample
  • Minimum SDK: 15
  • Blank Activity
  • Activity name: MainActivity

You now have Android's app module, but we also need to add a new Java module for greenDAO generation project. For this, select File > New > New module... and choose a Java Library, just as it's shown on the screenshot below.

Android Studio New Java module

Press Next and rename the library to greendao-gen and the Java class name to MainGenerator. Leave all other settings untouched and press Finish.

You should now see a following project structure:
Android GreenDAO project structure

And so the only thing we need now is to attach greenDAO dependencies and we're good to go!

Open our app's build.gradle file and add compile 'de.greenrobot:greendao:2.1.0' to the dependencies scope. 2.1.0 is the last version available at the time of writing this tutorial, but please always check it here.

Below you can check all dependencies of our app module.
Gradle app module dependencies

What we have added was a core dependency for our app. Now, we need to add a generator to the Java module. For this, just add a following line to the dependencies in greendao-gen module's build.gradle file: compile 'de.greenrobot:greendao-generator:2.1.0' (please check the latest version here). The overall file should look like this:

GreeDAO generation module dependencies

Sync all Gradle files to make sure there isn't some nasty error around :) If everything's OK, we can actually add some code!

For the demonstration purposes, I will show how to add two tables: User and Repo with one-to-many dependency and with a few fields. Also, the database-related classes will be created in the .db sub package of our main package.

Open MainGenerator class and paste the below code.


package com.example;

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;

public class MainGenerator {

    private static final String PROJECT_DIR = System.getProperty("user.dir");

    public static void main(String[] args) {
        Schema schema = new Schema(1, "com.abc.greendaoexample.db");
        schema.enableKeepSectionsByDefault();

        addTables(schema);

        try {
            /* Use forward slashes if you're on macOS or Unix, i.e. "/app/src/main/java"  */
            new DaoGenerator().generateAll(schema, PROJECT_DIR + "\\app\\src\\main\\java");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addTables(final Schema schema) {
        Entity user = addUser(schema);
        Entity repo = addRepo(schema);

        Property userId = repo.addLongProperty("userId").notNull().getProperty();
        user.addToMany(repo, userId, "userRepos");
    }

    private static Entity addUser(final Schema schema) {
        Entity user = schema.addEntity("User");
        user.addIdProperty().primaryKey().autoincrement();
        user.addStringProperty("name").notNull();
        user.addShortProperty("age");

        return user;
    }

    private static Entity addRepo(final Schema schema) {
        Entity repo = schema.addEntity("Repo");
        repo.addIdProperty().primaryKey().autoincrement();
        repo.addStringProperty("title").notNull();
        repo.addStringProperty("language");
        repo.addIntProperty("watchers_count");

        return repo;
    }
}

PROJECT_DIR is initialized with our project's main path. The scheme tells us that it's the first version of the database and that it should reside in com.abc.greendaoexample.db package (you should update the version number just to keep track of the updates). Also, we enable the keep sections, for the ability to modify our models without the fear that those modifications will be overridden by a next generation.

We then add the tables and generate the code with generateAll() method. As user can have many repositories, we add a dependency through a userId long property in Repo table and userRepos in User table.

In order to generate everything, either right click on MainGenerator class and choose Run 'MainGenerator.main()' or press on the run button on the top bar. You will then be presented with the Run window and after 1-3 seconds you will see that new classes have been added to the .db sub package. Expand it and check what's there. Repo should have a relation to its user and the user should have the list of repos. Both of them should have keep section comments.

And that's it! You now have greenDAO fully integrated into your project. Actually, by following the same steps (without new project creation, obviously), you could've integrated greenDAO into your existing project as well!

Now, I won't show what to do with the created classes, as I would basically repeat the example project here, so please, take a look at it, if you don't know what to do next. It is really straight forward and there shouldn't be any surprises for you ;)

As always, I hope you have enjoyed this tutorial, and please leave your comments below if you have any ;) Thanks!

Antonina Tkachuk

I'm an Android Developer, writing code for living and for fun. Love beautiful apps with a clean code inside. Love travelling and reading.