Practical Package for Greendao

Source: Internet
Author: User

The previous introduction of the use of the next Greendao, from the previous introduction seems to be a bit so easy. Yes, that's so easy. Once there was a great God who said that as a qualified programmer is going to learn something else, a little bit of their own ideas. In order to show that I am a more qualified programmer, today and you introduce the next Greendao of the more practical package. If you haven't had time to learn the practical details of Greendao, please go to Greendao for more detailed use. Long story short, we formally begin to introduce. First we create two new tables, namely the customer and the student table. The resulting file is shown below.

(i) Daomaster,daosession,devopenhelper objects under encapsulation


Its specific code is shown in Daomanager.java.

Package Com.jamy.daoutils;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Com.jamy.dao.daomaster;import com.jamy.dao.daosession;import de.greenrobot.dao.query.querybuilder;/** * Created by Jamy on 2016/6/16.   * Database Management * 1. Create DATABASE * 2. Create DATABASE table * 3. Make additions and deletions to the database * 4. Upgrade the database */public class Daomanager {private static final String    TAG = DaoManager.class.getSimpleName (); private static final String db_name= "jamy.db";//database name private volatile static Daomanager mdaomanager;//multithreaded Access Priv    Ate static Daomaster.devopenhelper mhelper;    private static Daomaster Mdaomaster;    private static daosession mdaosession;    private static Sqlitedatabase db;    Private context context; /** * Use singleton mode to get the object that operates the database * @return */public static Daomanager getinstance () {Daomanager instance = N        Ull                    if (mdaomanager==null) {synchronized (Daomanager.class) {if (instance==null) { Instance = new DAomanager ();                Mdaomanager = instance;    }}} return Mdaomanager; }/** * Initializes the context object * @param context */public void init (context context) {This.context = Contex    T             }/** * Determines if the database exists and if it does not exist create * @return */public Daomaster Getdaomaster () {if (null = = Mdaomaster) {            Mhelper = new Daomaster.devopenhelper (context,db_name,null);        Mdaomaster = new Daomaster (Mhelper.getwritabledatabase ());    } return mdaomaster;            /** * Complete additions and deletions to the database find * @return */public daosession getdaosession () {if (null = = Mdaosession) {            if (null = = Mdaomaster) {mdaomaster = Getdaomaster ();        } mdaosession = Mdaomaster.newsession ();    } return mdaosession; /** * Set debug mode on or off, default off * @param flag */public void Setdebug (Boolean flag) {QueryBuilder.LOG        _sql = Flag;Querybuilder.log_values = Flag;        }/** * Close database */public void CloseDataBase () {closehelper ();    Closedaosession ();            } public void Closedaosession () {if (null! = mdaosession) {mdaosession.clear ();        Mdaosession = null;            }} public void Closehelper () {if (mhelper!=null) {mhelper.close ();        Mhelper = null; }    }}
Daomanager is the main way to get the corresponding object through a single-column pattern, and to initialize all objects.


(ii) Encapsulation of a common base class that can operate on different data tables

As shown in its collective code Basedao.java.

Package Com.jamy.daoutils;import Android.content.context;import Android.util.log;import Com.jamy.dao.CustomerDao; Import Com.jamy.dao.daosession;import java.util.list;import de.greenrobot.dao.query.querybuilder;/** * Wrap all the created tables in the same section into this Basedao * Created by Jamy on 16/6/16.    */public class basedao<t>{public static final String TAG = BaseDao.class.getSimpleName ();    public static Final Boolean dubug = true;    Public Daomanager Manager;    Public Daosession daosession;        Public Basedao (Context context) {manager = Daomanager.getinstance ();        Manager.init (context);        Daosession = Manager.getdaosession ();    Manager.setdebug (Dubug);     /************************** Database insert Operation ***********************//** * Insert a single object * @param object * @return        */Public Boolean insertobject (T object) {Boolean flag = false;        try {flag = manager.getdaosession (). Insert (object)! =-1? true:false; } catch (Exception e) {LOG.E (TAG, e.tostring ());    } return flag; }/** * Inserts multiple objects and opens a new thread * @param objects * @return */public boolean insertmultobject (final list<t        > Objects) {boolean flag = false;        if (null = = Objects | | objects.isempty ()) {return false; try {manager.getdaosession (). Runintx (New Runnable () {@Override public void Run () {for (T object:objects) {manager.getdaosession (). Insertorreplace (                    object);            }                }            });        Flag = true;            } catch (Exception e) {log.e (TAG, e.tostring ());        Flag = false; }finally {//manager.        CloseDataBase ();    } return flag;  /************************** Database Update operation ***********************//** * Data modification As Object * It must know the primary key ID of the object * @param Object * @return */public void Updateobject (T object) {if (null = = object) {return;        try {manager.getdaosession (). Update (object);        } catch (Exception e) {log.e (TAG, e.tostring ()); }}/** * Bulk update data * @param objects * @return * * * public void Updatemultobject (Final list<t> o        Bjects, Class clss) {if (null = = Objects | | objects.isempty ()) {return; try {Daosession.getdao (CLSS). Updateintx (New Runnable () {@Override Publ                    IC void Run () {for (T object:objects) {daosession.update (object);        }                }            });        } catch (Exception e) {log.e (TAG, e.tostring ());      }}/************************** Database delete operation ***********************//** * Delete a database table * @param CLSS * @return        */Public Boolean deleteAll (Class clss) {Boolean flag = false;        try {    Manager.getdaosession (). DELETEALL (CLSS);        Flag = true;            } catch (Exception e) {log.e (TAG, e.tostring ());        Flag = false;    } return flag;            }/** * Delete an object * @param object * @return */public void DeleteObject (T object) {try {        Daosession.delete (object);        } catch (Exception e) {log.e (TAG, e.tostring ()); }}/** * Asynchronously bulk Delete data * @param objects * @return */public boolean deletemultobject (final list<t& Gt        objects, Class CLSS) {Boolean flag = false;        if (null = = Objects | | objects.isempty ()) {return false; try {Daosession.getdao (CLSS). Deleteintx (New Runnable () {@Override Publ                    IC void Run () {for (T object:objects) {Daosession.delete (object);            }                }            });        Flag = true; } CatCH (Exception e) {log.e (TAG, e.tostring ());        Flag = false;    } return flag; }/************************** database query operation ***********************//** * get a table name * @return */Public String    Gettablename (Class object) {return Daosession.getdao (object). Gettablename ();        /** * The object that queries an ID exists * @param * @return */public Boolean isexitobject (Long Id,class object) {        querybuilder<t> QB = (querybuilder<t>) Daosession.getdao (object). QueryBuilder ();        Qb.where (CustomerDao.Properties.Id.eq (Id));        Long length = Qb.buildcount (). Count (); Return length>0?    True:false; /** * Query * @param ID * Based on PRIMARY KEY ID * @return */public T Querybyid (Long Id,class object) {return (    T) Daosession.getdao (object). Loadbyrowid (ID); /** * Query for objects under a condition * @param object * @return */public list<t> queryobject (Class object,string     Where,string...params) {   Object obj = null;        list<t> objects = null;            try {obj = Daosession.getdao (object);            if (null = = obj) {return null;        } objects = Daosession.getdao (object). Queryraw (Where,params);        } catch (Exception e) {log.e (TAG, e.tostring ());    } return objects; /** * Query All Objects * @param object * @return */public list<t> Queryall (Class object) {List        <T> objects = null;        try {objects = (list<t>) Daosession.getdao (object). Loadall ();        } catch (Exception e) {log.e (tag,e.tostring ());    } return objects; /*************************** Close the database *************************//** * Shut down the database is generally used in odestory */public void Cl    Osedatabase () {manager.closedatabase (); }}
(iii) allow different data table objects to inherit Basedao

The specific code is shown in Studentmanager.java and Customermanager.java (since the two managers in this demo are similar, they only show Studentmanager.java).

Package Com.jamy.daoutils;import Android.content.context;import Com.jamy.dao.customerdao;import Com.jamy.entity.customer;import Com.jamy.entity.student;import Java.util.arraylist;import Java.util.List;import de.greenrobot.dao.query.querybuilder;/** * Created by Jamy on 16/6/16.         * Add different query conditions to this class */public class Studentmanager extends basedao<student>{public Studentmanager (context context) {    Super (context); /*************************** database Query *************************//** * Query object by ID * @param ID * @return *    /Private Student Loadbyid (long id) {return Daosession.getstudentdao (). Load (ID);  /** * Gets the primary key ID of an object * @param student * @return */Private long GetID (student student) {return    Daosession.getstudentdao (). GetKey (student); }/** * Gets the Customer object by name * @return */private list<student> Getstudentbyname (String key) {Q Uerybuilder QueryBuilder = Daosession.getstudentdao (). QuerybuildER ();        Querybuilder.where (CustomerDao.Properties.Name.eq (key));        int size = Querybuilder.list (). Size ();        if (Size > 0) {return querybuilder.list ();        }else{return null; }}/** * Gets the Customer object by name * @return */private list<long> Getidbyname (String key) {List        <Student> students = getstudentbyname (key);        list<long> ids = new arraylist<long> ();        int size = Students.size ();            if (Size > 0) {for (int i = 0;i < size;i++) {Ids.add (Students.get (i). GetId ());        } return IDs;        }else{return null;    }}/*************************** Database delete *************************//** * Database deletion based on ID * @param ID * *    private void Deletebyid (Long id) {Daosession.getstudentdao (). Deletebykey (ID); /** * Delete database operations based on ID sync * @param ids */private void Deletebyids (list<long>IDS) {Daosession.getstudentdao (). Deletebykeyintx (IDs); }/*********************************** * Add some student-specific database operation statements at a time * ************************************/}
for different data tables, some unique query conditions can be placed in the Studentmanager class (because different data tables may require a similar query condition), which makes it easy to query.

(iv) encapsulate the created multi-Table Manager object in a class

Its specific code is shown in Daoutils.java.

Package Com.jamy.daoutils;import Android.content.context;import Android.util.log;import Com.jamy.dao.CustomerDao; Import Com.jamy.dao.daosession;import Com.jamy.dao.studentdao;import Com.jamy.entity.customer;import Com.jamy.entity.student;import Java.util.arraylist;import Java.util.list;import De.greenrobot.dao.AbstractDao; Import de.greenrobot.dao.query.querybuilder;/** * Created by Jinfangmei on 2016/6/16.    */public class daoutils{private static Customermanager Customermanager;    private static Studentmanager Studentmanager;    public static context context;    public static void init (context context) {Daoutils.context = Context.getapplicationcontext ();        }/** * Single-column mode gets Customermanager object * @return */public static Customermanager Getcustomerinstance () {        if (Customermanager = = null) {Customermanager = new Customermanager (context);    } return Customermanager; }/** * Single-row mode gets Studentmanager Object * @return */PubLic static Studentmanager getstudentinstance () {if (Studentmanager = = null) {Studentmanager = new stude        Ntmanager (context);    } return Studentmanager; }}
It is important to note that because the context in Daoutils is modified by static, the context here is used ApplicationContext (to prevent the memory leak due to the end of activity).
The above step-by-step package has been completed, and the following call in Mainactivity is not a good use to try. Ha ha.

The specific code for the Mainactivity.java is shown below.

Package Com.jamy.testgreendao;import Android.content.context;import android.support.v7.app.AppCompatActivity; Import Android.os.bundle;import android.util.log;import Android.view.view;import Android.widget.button;import Com.jamy.daoutils.daoutils;import Com.jamy.entity.customer;import Com.jamy.entity.student;import Java.util.arraylist;import Java.util.list;public class Mainactivity extends Appcompatactivity implements    view.onclicklistener{private Button Maddbutton;    Public Button Mdeletebutton,mupdatebutton,mquerybutton;    Private list<object> students;    Private list<customer> customers;    Private context context;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();    Daoutils.init (Mainactivity.this);        } private void Initview () {customers = new arraylist<customer> ();   Students = new arraylist<object> ();     Maddbutton = (Button) Findviewbyid (R.id.addbutton);        Mdeletebutton = (Button) Findviewbyid (R.id.deletebutton);        Mupdatebutton = (Button) Findviewbyid (R.id.uodatebutton);        Mquerybutton = (Button) Findviewbyid (R.id.querybutton);        Maddbutton.setonclicklistener (this);        Mdeletebutton.setonclicklistener (this);        Mupdatebutton.setonclicklistener (this);    Mquerybutton.setonclicklistener (this); } @Override public void OnClick (View v) {switch (V.getid ()) {R.id.addbutton:for (i                  NT i=0;i<4;i++) {Student Student = new Student ();                  Student.setname ("Jamy");                  Student.setage (110+i);                  Student.setdepartment ("A1113" +i);              Students.add (student);                  } for (int i=0;i<4;i++) {Customer customer = new Customer ();                  Customer.setname ("Jin" +i); Customer.setaddress ("Shenzhen"+i);                  Customer.settype ("CEO");              Customers.add (customer);              } daoutils.getcustomerinstance (). Insertmultobject (Customers);          Break Case R.id.deletebutton:daoutils.getcustomerinstance (). Deletebyids (Daoutils.getcustomerinstance (). GetIdByName              ("jin2"));          Break Case r.id.querybutton:list<customer> List = Daoutils.getcustomerinstance ().              Queryall (Customer.class);                  for (int i=0;i<list.size (); i++) {Customer customer = List.get (i); LOG.D ("Jamy", "ID:" +customer.getid () + "Name:" +customer.getname () + "Address:" +customer.getaddress              () + "Type:" +customer.gettype ());          } break;              Case R.id.uodatebutton:customer customer = new Customer ();              Customer.setid (1l);              Customer.setname ("Jinfangmei");        Customer.settype ("CEO");      Customer.setaddress ("Shenzhen0"); Daoutils.getcustomerinstance (). Updateobject (Customer),//if (null! = Customers) {//for (int                  I=0;i<customers.size (); i++) {//LOG.D ("Jamy", Customers.get (i). GetId (). toString ());// }//}//list<long> ids = Daoutils.getidbykey ("jin1");//LOG.D ("Jamy", IDS.T              Ostring ());      Break        }} @Override protected void OnDestroy () {Super.ondestroy (); Daoutils.getcustomerinstance ().    CloseDataBase (); }}

OK, call the next, the feeling is still good. It's not perfect, but at least it will work. The above is my humble greendao to carry out some simple package, know that is not very perfect, I hope you give more criticism and suggestions, without your advice without my gradual growth. Two blog posts done, haha.









Practical Package for Greendao

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.