Contents
This tutorial will walk you through a simple greenDAO example project, DaoExample. Feel free to clone the code and run it, or just view the files directly on GitHub.
DaoExample is a simple Android app for taking notes. You can add new notes by typing in some text, and delete notes by clicking on an existing note.
The Note entity and DAO class
Let’s jump right into the code: in the src folder you will find the entity class for a note, Note.java. It is persisted to the database and contains all data that is part of a note, like an id, note text and the creation date.
1 2 3 4 5 6 7 8 9 10 11 12 | @Entity(indexes = { @Index(value = "text, date DESC", unique = true) }) public class Note { @Id private Long id; @NotNull private String text; private Date date; ... |
In general, an entity is a class persisted in the database (e.g. a row for each object). An entity contains properties, which are mapped to database columns.
Now make the project, for example by using Build > Make project in Android Studio. This triggers greenDAO to generate DAO classes, like NoteDao.java, that will help us add notes to a database.
Inserting and deleting notes
To learn how to add some notes, take a look at the NoteActivity class. First, we have to prepare a DAO object for our Note class, which we do in onCreate():
1 2 3 | // get the note DAO DaoSession daoSession = ((App) getApplication()).getDaoSession(); noteDao = daoSession.getNoteDao(); |
When the user clicks the add button the method addNote() is called. There, we create a new Note object and pass it to the DAOs insert() method to insert it into the database:
1 2 3 4 5 6 7 | Note note = new Note(); note.setText(noteText); note.setComment(comment); note.setDate(new Date()); note.setType(NoteType.TEXT); noteDao.insert(note); Log.d("DaoExample", "Inserted new note, ID: " + note.getId()); |
Note that we did not pass an id when creating the note. In this case the database decides on the note id. The DAO takes care of automatically setting the new id before returning from insert (see the log statement).
Deleting a note is also straight forward, see NoteClickListener:
1 | noteDao.deleteByKey(id); |
Updating notes and more
What is not shown in the example, but is just as easy: to update a note, just modify any of its properties and call the DAOs update() method:
1 2 | note.setText("This note has changed."); noteDao.update(note); |
There are additional methods to insert, query, update or delete entities. Check out the methods of the AbstractDao class which all DAOs inherit from to learn more.
Setting up the database
You already saw DAOs, but how do you initialize greenDAO and the underlying database? Usually you need to init a DaoSession, which is typically done once for the whole app inside the Application class.
1 2 3 4 | // note: DevOpenHelper is for dev only, use a OpenHelper subclass instead DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db"); Database db = helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); |
For simplicity the database is created with the helper class DevOpenHelper, provided by the generated DaoMaster class. It is an implementation of the OpenHelper class in DaoMaster, which does all database set up for you. No need to write “CREATE TABLE” statements.
However, DevOpenHelper will drop all tables on schema changes (in onUpgrade()). So we recommend you create and use a subclass of DaoMaster.OpenHelper instead.
Activities and fragments may then call getDaoSession() to get access to all entity DAOs, as seen above when inserting and deleting notes.
Extending and adding entities
In order to extend our note or to create new entities, you simply modify or create Java classes and annotate them in the same way. Then rebuild your project.
See Modelling entities for details.
Next steps
Now that you have an impression of what greenDAO looks like, it’s a good idea to get your hands dirty and try it for yourself. Continue by having a look at the full documentation, starting with the Introduction.
Finally, if you do not find what you are looking for, please let us know.
How do you close the DaoSession ?
If I have 3 activities and I need to use greenDao in eatch of them, I will have to create a new instance of DaoSession every time and I never close this sessions … It’s that ok ?
How can I do this the right way ?
Thank you,
Alin
My recommendation is to start with an application-scope DaoSession. For example, have a subclass of Application and register your Application class in the manifest (or use some kind of singleton).
I started the documentation on sessions to provide some more details (more details to come soon): http://greendao-orm.com/documentation/sessions/
If you have more questions, feel free to ask, preferably in the greenDAO Google group: https://groups.google.com/forum/#!forum/greendao
Hi.. not sure where to post this question… But was wondering if greenDAO support persistence of following type of class
class A {
….. other fields….
List<A> fields;
}
can this be persisted? I am working on a project that involves such a scenario and was wondering if there is support for this.
thanks in advance.
VK, the best place to ask questions is the Google group: https://groups.google.com/forum/#!forum/greendao
I’m not sure if I understood your use case. In case you want to model entities in a tree-like structure: yes, that is possible. I just updated the docs. Have a look at “Modelling Tree Relations” on this page: http://greendao-orm.com/documentation/relations/
If you have further questions, let us continue the discussion in the Google group.