This tutorial will walk you through an simple greenDAO example project. It is available on and consists of two subprojects (folders): DaoExample and DaoExampleGenerator. You can either clone the git repository to get the code and run it, or just view view the files directly on github.
If you checked DaoExample out from the git repository, you can run it as an Android Application. As you can see, it’s a simple app for taking notes. You can add new notes by typing in some text, and delete notes by clicking on an existing note.
Pre-generated code and creating the table
Now, let’s look at some code. In the folder src-gen, you’ll find some already generated artifacts:
1) Note.java is a Java class containing all data a note has
2) NoteDao.java is the DAO class, your interface to work with Note objects
You can always generate Note and NoteDao again using the DaoExampleGenerator project. But let’s stick to DaoExample for a minute. Using the DaoMaster class you can aquire a convenience SQLiteOpenHelper:
As you notice, you do not have to code “CREATE TABLE” SQL scripts. greenDAO does that for you.
Inserting and deleting notes
So once we have a table for our notes, we can put in some notes in the database. This is done in the NoteActivity class. In the onCreate method we prepare a DAO object:
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();
Now have a look at the addNote method, how you insert a new note in the database:
Log.d("DaoExample", "Inserted new note, ID: " + note.getId());
Just create a Java object and call insert on the DAO. When the insert method returns, the database id of the just inserted note is already assigned to the object, as you can see in the log statment.
Deleting a note is also straight forward; have a look at the onListItemClick method:
If you want, you can explore other DAO methods like loadAll and update.
Data model and code generation
In order to extend the note or to create new entities, you should have a look at the DaoExampleGenerator project. It contains a single class containing the data model definition in code:
Entity note= schema.addEntity("Note");
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
As you can see, you create a Schema object, to which you can add entities. An entitiy is a class tied to a database table. An entity contains properties, which are mapped to database columns.
Once the schema is completely defined, you can trigger the code generation. This is how the Note.java and NoteDao.java files where created.
Now, that you got an impression what greenDAO looks like, it’s a good idea to get your hands dirty and try it for yourself. Also, please have a look at the documentation. If you do not find what you are looking for, please use one support options.