I believe that in the normal development process, we will certainly be more or less in touch with SQLite. However, when using it, we often need to do a lot of extra work, such as writing SQL statements and parsing query results. So, the ORM framework for Android was born, and now the mainstream framework is Ormlite, Sugarorm, Active Android, Realm and Greendao. And today's protagonist is Greendao, below, I will explain how to use Greendao on Android Studio, and combined with code to summarize some of the experience in the use of the process.
Simply put, Greendao is a lightweight and fast ORM solution that maps objects to a SQLite database. (Greendao is a light & fast ORM solution, maps objects to SQLite databases.)
As for the concept of ORM (object Relation Mapping-relational mapping), refer to Wikipedia.
Main objectives of Greendao design
1. A streamlined library
2. Maximize Performance
3. Minimized memory Overhead
4. Easy-to-use APIs
5. Highly optimized for Android
Main features of Greendao design
1.greenDAO performance is much higher than similar ormlite, the specific test results can be seen in the official website
2.greenDAO supports direct storage of protocol buffer (PROTOBUF) protocol data, and if you interact with the server through the PROTOBUF protocol, no mapping is required.
3. Unlike an ORM framework that uses annotations, such as Ormlite, Greendao uses "code generation", which is why its performance can be significantly improved.
In order to use Greendao in our Android project, we need to build a separate Java project to automatically generate the beans, DAO, Daomaster, Daosession, and so on that will be used in subsequent Android projects.
About the concepts and functions of the above categories, I will explain them in detail in the following code (note).
Of course, you can also find the relevant information on the official website.
Start ==================
I. Create a new Android project, Greendao generated by the Bean, DAO, Daomaster, daosession and other classes will exist in this Android project.
Two. New "greendao generator" Module (Pure JAVA Engineering)
1. Complete the corresponding package name and class name, through the Java Library, File--new----new Module.
2. Write the Exampledaogenerator class, note: Our Java project has only one class, its content determines the output of "greendao generator", you can in this class through objects, relationships, etc. to create a database structure, Below I will explain the code in detail in the form of comments.
Package com.example;
Import De.greenrobot.daogenerator.DaoGenerator;
Import de.greenrobot.daogenerator.Entity;
Import De.greenrobot.daogenerator.Schema;
public class Exampledaogenerator {
public static void Main (string[] args) throws Exception {
As you can see, you create a schema object that is used to add entities (entity).
The two parameters represent: the database version number and the package path of the automatically generated code.
Schema schema = new schema (1, "Teach.focus.testgreendao");
Of course, if you want, you can also specify the directory where the generated beans and DAO classes are located, as shown below:
Schema schema = new schema (1, "Me.itangqi.bean");
Schema.setdefaultjavapackagedao ("Me.itangqi.dao");
// 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addNote(schema);
//Addnotes (Schema);
//Finally we will use the Generateall () method of the Daogenerator class to generate the code automatically, where you need to change the output directory as you like, and you are currently src/main/java/in the Android project Teach.focus.testgreendao is generated below.
//In fact, the path of the output directory can be set in Build.gradle, interested friends can search by themselves, here is no longer detailed.
New Daogenerator (). Generateall (Schema, "App/src/main/java");
}
/** * @param schema */private static void Addnote (schema Schema) {//an Entity (Class) is associated to a table in the database where table name is "note" (both class name) entity No Te = schema.addentity ("Note"); You can also re-name the table//Note.settablename ("NODE"); Greendao automatically creates a table field based on the attribute value of the entity class and assigns the default value//Next you can set the fields in the table: Note.addidproperty (); Note.addstringproperty ("text"). Notnull (); Unlike using hump naming methods in Java, naming in the default database uses uppercase and underscores to divide words. For example, the A property called "CreationDate" would become a database column "Creation_date". Note.addstringproperty ("comment"); Note.adddateproperty ("date");} /** * @param schema */private static void Addnotes (schema Schema) {//an Entity (Class) is associated to a table in the database where table name is "note" (both class name) entity N OTE = schema.addentity ("Notes"); You can also re-name the table//Note.settablename ("NODE"); Greendao automatically creates a table field based on the attribute value of the entity class and assigns the default value//Next you can set the fields in the table: Note.addidproperty (); Note.addstringproperty ("text"). Notnull (); Unlike using hump naming methods in Java, naming in the default database uses uppercase and underscores to divide words. For example, a property called "CreationDate" will become a database column "Creation_date". Note.addstringproperty ("comment"); Note.adddateproperty ("date");}
}
Three. Generate a DAO file (database)
Perform the generator project, and if everything works, you will see the following log in the console, and under the main project "java-gen" you will find Daomaster, Daosession, Notedao, note a total of 4 class files.
If there is an error here, you can troubleshoot based on the error log, mainly to see if the output directory exists? Is the other configuration correct?
Four. Database operation in ANDROID project
Noteactivity.java
public class Noteactivity extends Listactivity {
Private SQLi Tedatabase DB;
Private EditText EditText;
Private Daomaster Daomaster;
Private daosession daosession;
Private cursor cursor;
public static final String TAG = "daoexample";
@Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_note); The official recommendation is to place the method that gets the Daomaster object into the application layer, which avoids creating the Session object multiple times setupdatabase (); Gets the Notedao object Getnotedao (); String textColumn = NoteDao.Properties.Text.columnName; String = TextColumn + "COLLATE localized ASC"; cursor = Db.query (Getnotedao (). Gettablename (), Getnotedao (). Getallcolumns (), NULL, NULL, NULL, NULL, by-do); String[] from = {textColumn, NoteDao.Properties.Comment.columnName}; Int[] to = {Android. R.id.text1, Android. R.ID.TEXT2}; Simplecursoradapter adapter = new Simplecursoradapter (this, Android. R.layout.simple_list_item_2, cursor, from, to); Setlistadapter (adapter); EditText = (editText) Findviewbyid (r.id.edittextnote);} private void Setupdatabase () {///through Daomaster's inner class devopenhelper, you can get a handy sqliteopenhelper object. Perhaps you have noticed that you do not need to write SQL statements such as "create table", because GreeNdao has done it for you. Note: The default daomaster.devopenhelper will delete all tables when the database is upgraded, meaning that this will result in loss of data. Therefore, in a formal project, you should also do a layer of encapsulation, to achieve the security of the database upgrade. Daomaster.devopenhelper helper = new Daomaster.devopenhelper (This, "notes-db", null); db = Helper.getwritabledatabase (); Note: This database connection belongs to Daomaster, so multiple sessions refer to the same database connection. Daomaster = new Daomaster (db); Daosession = Daomaster.newsession ();} Private Notedao Getnotedao () {return Daosession.getnotedao ();} /** * button click on the Listener event * * @param view */public void Onmybuttonclick (view view) {switch (View.getid ()) {case R.I D.buttonadd:addnote (); Break Case R.id.buttonsearch:search (); Break DEFAULT:LOG.D (TAG, "What have gone wrong?"); Break }}private void Addnote () {String notetext = Edittext.gettext (). toString (); Edittext.settext (""); Final DateFormat df = dateformat.getdatetimeinstance (Dateformat.medium, Dateformat.medium); String comment = "Added on"+ Df.format (new Date ()); Insert operation as simple as you create a Java object Note Note = new Note (null, notetext, comment, New Date ()); Getnotedao (). Insert (note); LOG.D (TAG, "Inserted new note, ID:" + Note.getid ()); Cursor.requery ();} The private void Search () {///query class represents a query that can be executed repeatedly by querying query = Getnotedao (). QueryBuilder (). where (Noteda O.properties.text.eq ("Test1")). ORDERASC (NoteDao.Properties.Date). build ();
Query results returned as List
List notes = Query.list ();
Built-in QueryBuilder class with two flags for easy output execution of SQL statements and values of passed parameters
Querybuilder.log_sql = true;
Querybuilder.log_values = true;
}
/** * ListView 的监听事件,用于删除一个 Item * @param l * @param v * @param position * @param id */@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) { // 删除操作,你可以通过「id」也可以一次性删除所有 getNoteDao().deleteByKey(id);
Getnotedao (). DeleteAll ();
LOG.D (TAG, "Deleted Note, ID:" + ID);
Cursor.requery ();
}
}
Five. Running results
Everything is ready, let's see how it works! Run the program, execute the Add button separately, delete (click on the List Item) with the query button, you can get the following log in the console:
demo:http://download.csdn.net/detail/dfskhgalshgkajghljgh/9508862
Greendao of Android ORM framework