Greendao use of Android ORM framework

Source: Internet
Author: User
Tags dateformat sqlite database

Original: http://itangqi.me/android/using-greendao-experience/

Objective

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.

About Greendao

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
    • A streamlined library

    • Maximized performance

    • Minimized memory overhead

    • Easy-to-use APIs

    • Highly optimized for Android

Main features of Greendao design
    • Greendao performance is much higher than similar ormlite, the specific test results can be seen on the official website

    • 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.

    • Unlike the ORM framework, which uses annotations, such as Ormlite, Greendao uses "code generation", which is why its performance can be greatly improved.

DAO CODE GENERATION PROJECT

This is the core concept: 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 that will be used in subsequent Android projects. and other classes.

CORE CLASSES & Modelling Entities

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.

Let's get started. Configuring the "greendao generator" module in ANDROID Engineering
    1. Create a new Java-level "java-gen" directory under the. Src/main directory to hold the beans, DAO, Daomaster, Daosession, and other classes generated by Greendao.

    2. Configure Android Engineering (APP) Build.gradle, add sourcesets and dependencies, respectively.

Sourcesets {main {java.srcdirs = [' Src/main/java ', ' Src/main/java-gen '}}
Compile ' de.greenrobot:greendao:1.3.7 '
Two. New "greendao generator" Module (Pure JAVA Engineering)
    1. Fill in the appropriate package name and class name, using the Java Library, File--new---new Module.

    2. Configure the Build.gradle of the Daoexamplegenerator project to add dependencies.

Compile ' de.greenrobot:greendao-generator:1.3.1 '
    1. 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.

public class exampledaogenerator {    public static void  Main (String[] args)  throws exception {        //   As you can see, you have created a schema object for adding entities (entity).         //  two parameters represent: the database version number and the package path of the automatically generated code.         schema schema = new schema (1,  " Me.itangqi.greendao ");//       of course, if you like, you can also specify the generated  Bean  and  dao separately The directory where the   class is located, as follows://      schema schema = new schema (1,   "Me.itangqi.bean");//      schema.setdefaultjavapackagedao ("Me.itangqi.dao The;        //  mode (schema) also has two default  flags, which are used to mark  entity   Whether it is  activie  and whether to use  keep sections.         // scheMa2.enableactiveentitiesbydefault ();        //  Schema2.enablekeepsectionsbydefault ();        //  Once you have a   After you schema  the object, you can use it to add an entity (entities).         addnote (Schema);         //  finally we will use the  DAOGenerator  class  generateall ()   method to generate the code automatically, where you need to change the output directory  java-gen).         //  in fact, the path of the output directory can be set in  build.gradle , interested friends can search by themselves, There is no further explanation here.         new daogenerator (). Generateall (schema,  "/Users/ Tangqi/android-dev/androidstudioprojects/mygreendao/app/src/main/java-gen ");    }     /**     *  @param  schema     */     private static void addnote (Schema schema)  {&Nbsp;       //  an Entity (Class) is associated to a table in the database, where the table name is "note" (both class name)          entity note = schema.addentity ("note");         //  You can also name the table again         //  Note.settablename ("NODE");        // greendao  Table fields are automatically created based on the attribute values of the entity class and assigned the default values         //  next you can set the field in the table:         note.addidproperty ();         Note.addstringproperty ("text"). Notnull ();        //  with the  java Unlike the hump naming method used in  , 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. Generating a DAO file (database)
    • Perform generator project, if everything is OK, you will see the following log in the console, and in the main project "java-gen" will find Daomaster, daosession, Notedao, note a total of 4 classes of files.

If there is an error here, you can troubleshoot the error log, mainly to see if the output directory exists? Is the other configuration correct? such as

Four. Database operations in ANDROID Engineering

Here, we only create a nodeactivity class for testing and explaining the function of Greendao, deleting and checking.

    • Activity_note.xml

<?xml version= "1.0"  encoding= "Utf-8"? ><linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android "    android:layout_width=" Fill_parent "     android:layout_height= "fill_parent"     android:orientation= "vertical" >     <linearlayout        android:id= "@+id/ LinearLayout1 "        android:layout_width=" Fill_parent "         android:layout_height= "Wrap_content"          android:orientation= "Horizontal" >        <edittext             android:id= "@+id/editTextNote"              android:layout_width= "Wrap_content"               android:layout_height= "Wrap_content"              android:layout_weight= "1"              android:hint= "Enter new note"              android:inputtype= "Text" ></EditText>        < Button            android:id= "@+id/buttonAdd"             android:layout_width= "Wrap_content"             android:layout_height= "Wrap_content"             android:onclick= "OnMyButtonClick"             android:text= "Add" ></Button>      &nbsP;  <button            android:id= "@+ Id/buttonsearch "            android:layout_width=" Wrap_content "            android:layout_height=" Wrap_content "            android:onclick=" Onmybuttonclick "            android:text=" Search ></Button>    </LinearLayout>    <ListView         android:id= "@android: Id/list"          android:layout_width= "Fill_parent"         android:layout_ height= "Wrap_content" ></ListView></LinearLayout>
    • Noteactivity.java

public class noteactivity extends listactivity {    private  sqlitedatabase db;    private edittext edittext;     private daomaster daomaster;    private daosession daosession;     private Cursor cursor;    public static final  string tag =  "Daoexample";     @Override     public  Void oncreate (bundle savedinstancestate)  {         Super.oncreate (savedinstancestate);         setcontentview ( R.layout.activity_note);        //  Official recommendation will get  DaoMaster  object to the  Application  layer, which avoids creating the build  Session  object multiple times          setupdatabase ();         //  Get  NoteDao  Objects          Getnotedao ();        string textcolumn =  notedao.properties.text.columnname;        string orderby =  textColumn +  "&NBSP;COLLATE&NBSP;LOCALIZED&NBSP;ASC";         cursor = db.query (Getnotedao (). Gettablename (),  getnotedao (). GetAllColumns (),  Null, null, null, null, orderby);         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 convenient   The sqliteopenhelper  object.         //  Maybe you've noticed that you don't have to write "create table" like that  sql   statement, because  greenDAO  has done it for you.         //  Note: The default  DaoMaster.DevOpenHelper  is when the database is upgraded, Deleting all the tables means that this will result in the loss of data.         //  so, in a formal project, you should also do a layer of encapsulation to achieve a secure database upgrade.         daomaster.devopenhelper helper&Nbsp;= new daomaster.devopenhelper (this,  "notes-db",  null);         db = helper.getwritabledatabase ();           NOTE: The database connection belongs to  daomaster, so multiple  Session  refers 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) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; switch  (View.getid ())  {             case R.id.buttonAdd:                 addnote ();                 break;            case  r.id.buttonsearch:                 search ();                 break;            default:    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D (TAG,  "What has  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, simple as long as you create a  Java  object          note note = new note (Null, notetext, comment,  new date ());         getnotedao (). Insert (note);   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D (tag,  "INSERTED&Nbsp;new note, id:  " + note.getid ());         Cursor.requery ();     }    private void search ()  {  The        // Query  class represents a query that can be executed repeatedly          query query = getnotedao (). QueryBuilder ()                  .where (NoteDao.Properties.Text.eq ("Test1"))   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;.ORDERASC ( NoteDao.Properties.Date)                  .build ();//       query results with  List  return//       list notes = query.list ();        //  in The  QueryBuilder  class contains two Flag  for easy output execution of  SQL  statements and values of passed parameters          Querybuilder.log_sql = true;        querybuilder.log_values  = true;    }    /**     *  listview  Listener event for deleting a  Item     *  @param  l      *  @param  v     *  @param  position      *  @param  id     */     @Override      protected void onlistitemclick (Listview l, view v, int position,  long id)  {        //  Delete operation, you can also delete all the "id"         getnotedao (). Deletebykey (ID);//         getnotedao (). deletealL (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;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:

At last
      • Demo download link for this article: Https://github.com/tangqi92/MyGreenDAO

      • This tutorial is intended to introduce the basic usage and configuration of Greendao, more advanced and detailed use, see the official website

      • If there are any errors or omissions in this article, please correct me. At the same time I look forward to becoming friends with you, so welcome to the social network of mutual powder!!!

Greendao use of Android ORM framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.