Android Database Framework Greendao encapsulation, easy to understand, easy to expand

Source: Internet
Author: User

I. Overviewin the previous project, the Greendao of the ORM framework was exposed because of the database involved. Back on the Internet a large number of search and download learning, found that many are the official website of the translation or the official website demo Simple introductory explanation, but also for small white, do not know where to start, and ultimately give up the choice of local SQLite. after a short time, the application of Greendao has been a commonplace, so, in the last weekend took a few times on the official website of the demo disassembly package, and improve the function, as easy as possible to understand and expand, easy to use in the future directly. Second,Adddata/deletedata/changedata/querydata (corresponding to the database of the increase, deletion, change, check effect), due to time reasons, no interface. Spend too much time on this, also because this just want to share to everyone, behind everyone can download addThird, the CodeThe project is divided into three parts: DAO (Official Demo Generation Class), Manager (Specific function implementation Class), Utils (Encapsulation operation Class)DAO is not drying code, and the official website of the same. The Manager folder has the app and Daomanager class, the app is mainly initializes the new database, Daomanager is responsible for implementing the database operation function. App class:
Package Com.example.jekin.greendao.manager;import Android.app.application;import Android.content.context;import Com.example.jekin.greendao.dao.daomaster;import com.example.jekin.greendao.dao.daosession;/** * Created by Jekin on 2016/4/8.    */public class App extends application{public static app Minstance;    public static Daomaster Daomaster;    public static daosession daosession;    public static Daomanager Daomanager;        @Override public void OnCreate () {super.oncreate ();        Minstance = this;    Daomanager = Daomanager.getinstance (Getapplicationcontext ()); }/** * Get daomaster * * @param context * @return Daomaster */public static Daomaster Getdaomast        ER (context context) {Daomaster.openhelper helper = new Daomaster.devopenhelper (context, "person.db", null);        Daomaster = new Daomaster (Helper.getwritabledatabase ());    return daomaster; }/** * Get daosession * * @param context * @return Daosession     */public static daosession Getdaosession (context context) {if (daosession = = null) {if (Daoma            Ster = = null) {Daomaster = Getdaomaster (context);        } daosession = Daomaster.newsession ();    } return daosession; }}
Daomanager class:
Package Com.example.jekin.greendao.manager;import Android.content.context;import Com.example.jekin.greendao.dao.daosession;import Com.example.jekin.greendao.dao.person;import Com.example.jekin.greendao.dao.persondao;import Java.util.list;import De.greenrobot.mydao.query.DeleteQuery; Import De.greenrobot.mydao.query.querybuilder;import de.greenrobot.mydao.query.wherecondition;/** * Created by JeKin On 2016/4/8.    * Functional Implementation Classes */public class Daomanager {private static Daomanager instance;    private static Context AppContext;    Private Daosession mdaosession;    Private Persondao Persondao;            Public Daomanager () {} public static Daomanager getinstance (context context) {if (instance = = null) {            Instance = new Daomanager ();            if (AppContext = = null) {AppContext = Context.getapplicationcontext ();            } instance.mdaosession = app.getdaosession (context);        Instance.persondao = Instance.mDaoSession.getPersonDao (); }        return instance; }/** * ================person====================* * */Public list<person> Orderascperson () {R    Eturn Persondao.querybuilder (). ORDERASC (PersonDao.Properties.Id). List ();        }/** * Person Insert Function * * @return * @param: Album */public void InsertPerson (person person) {    Persondao.insert (person);    } public void Insertorreplaceperson (person person) {Persondao.insertorreplaceintx (person);    } public void Updateperson (person person) {persondao.update (person); }/** * Person lookup function *//Find condition * @param arg0 * @param conditions * @return: albumlist */Public        List<person> Queryperson (wherecondition arg0, wherecondition ... conditions) {        querybuilder<person> QB = Persondao.querybuilder ();        Qb.where (arg0, conditions);        list<person> personlist = Qb.list ();    return personlist; }    /**     *Person removes all features * * @param * @return */public void Deleteallperson () {persondao.deleteall ();        }/** * Person Delete function * * @return * @param: Album */public void Deleteperson (person person) {    Persondao.delete (person);        } public void Deletepersonbyname (String name) {querybuilder<person> QB = Persondao.querybuilder ();        deletequery<person> bd = Qb.where (PersonDao.Properties.Name.eq (Name)). Builddelete ();    Bd.executedeletewithoutdetachingentities (); }}
Utils Folder only Daoutils package class, easy to post-expansion, understand the words are easy to read
Package Com.example.jekin.greendao.utils;import Com.example.jekin.greendao.dao.person;import Com.example.jekin.greendao.dao.persondao;import Com.example.jekin.greendao.dao.jsoncode;import Com.example.jekin.greendao.manager.app;import java.util.list;/** * Created by Jekin on 2016/4/8. * Encapsulate the implementation of the database, hide implementation Details */public class Daoutils {//===================getpersondao======================== public stat        IC list<person> getpersonbyname (String name) {list<person> List = null;        List = App.daoManager.queryPerson (PersonDao.Properties.Name.eq (Name));    return list;        }//Find sort public static list<person> Getperson () {list<person> personlist = null;        Personlist = App.daoManager.orderAscPerson ();    return personlist; }//==============================insertdao==================================== public static void InsertPersonDao ( Jsoncode jsoncode) {//Add data for (int i = 0; i < Jsoncode.getperson (). SiZe ();        i++) {App.daoManager.insertPerson (Jsoncode.getperson (). get (i)); }} public static Boolean checkpersonexistandupdate (String name) {list<person> personlist = App.daoman        Ager.queryperson (PersonDao.Properties.Name.eq (Name));  if (personlist.size () > 0) {for (int i = 0; i < personlist.size (); i++) {Person person = New Person (Personlist.get (i). GetId (), Personlist.get (i). GetName (), Personlist.get (i). Gethigh (), Personlist.get (i).                Getage ());            App.daoManager.insertOrReplacePerson (person);        } return true;    } return false; }}
Finally, our boss came out, the main code is four sentencesmainactivity:
Package Com.example.jekin.greendao;import Android.os.bundle;import android.support.v7.app.AppCompatActivity; Import Android.util.log;import Android.view.view;import Android.widget.listview;import Android.widget.simpleadapter;import Com.example.jekin.greendao.dao.person;import Com.example.jekin.greendao.dao.jsoncode;import Com.example.jekin.greendao.manager.app;import Com.example.jekin.greendao.utils.daoutils;import com.google.gson.gson;import java.util.ArrayList;/** * Created by Jekin on 2016/04/12 * Data manipulation Class */public class Mainactivity extends Appcompatactivity {private static final String TAG1 =    "AddData";    private static final String TAG2 = "DeleteData";    private static final String TAG3 = "Changedata";    private static final String TAG4 = "Querydata"; Impersonate JSON data private String jsonstring = "{' Code ': ' '" ', ' success ': ' true ', ' person ': [{' Name ': ' Jekin ', ' High ': ' 173 ', ' age '    : '},{' name ': ' Mike ', ' High ': ' 178 ', ' age ': ' 24 '}]} ";    Find the condition of the data private String name = "Mike"; @OverrIDE protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Jsoncode Jsoncode = new Gson (). Fromjson (jsonstring, Jsoncode.class);        Add Data//check if the person object already exists, insert Boolean isexist = daoutils.checkpersonexistandupdate (name) if it does not exist;        if (!isexist) {Daoutils.insertpersondao (Jsoncode); }//Add after lookup data for (person Person:DaoUtils.getPerson ()) {LOG.E (TAG1, Person.geti            D (). ToString ());            LOG.E (TAG1, Person.getname (). toString ());            LOG.E (TAG1, Person.gethigh (). toString ());        LOG.E (TAG1, Person.getage (). toString ());        }//Condition delete App.daoManager.deletePersonByName (name);            for (person Person:DaoUtils.getPerson ()) {LOG.E (TAG2, Person.getid (). toString ());            LOG.E (TAG2, Person.getname (). toString ()); LOG.E (TAG2, Person.gethigh ().ToString ());        LOG.E (TAG2, Person.getage (). toString ());                    }//Condition modification if (daoutils.checkpersonexistandupdate (name)) {for (Person person:                Daoutils.getpersonbyname (name)) {LOG.E (TAG3, Person.getid (). toString ());                LOG.E (TAG3, Person.getname (). toString ());                LOG.E (TAG3, Person.gethigh (). toString ());            LOG.E (TAG3, Person.getage (). toString ()); }}//modified after query statement for (person Person:DaoUtils.getPerson ()) {LOG.E (TAG4, PE            Rson.getid (). toString ());            LOG.E (TAG4, Person.getname (). toString ());            LOG.E (TAG4, Person.gethigh (). toString ());        LOG.E (TAG4, Person.getage (). toString ()); }    }}
Iv. Conclusionno interface, so the slag in the Logcat output view, JSON data is analog data, if it is related to network data that is inconvenient to see the effect,please forgive me. Later expansion, only need to add the corresponding entity class and Xxdao binding Data class under the DAO folder, if other data manipulation functions are needed, it can be implemented in daoutils (refer to person, the main example of this object in code). The above is a personal summary of the Greendao, hoping to help more compatriots. Code if there is any problem, please point out in time, do not leave any pits for you, this is the second time to write a blog, a lot of advice! Finally, we recommend that you go to read a book "Android design Mode", because this demo inspiration is also from it, the code has been written, although useful to design patterns, but the concept is very vague, personal feeling is very suitable for my small white.
source Click to download

Android Database Framework Greendao encapsulation, easy to understand, easy to expand

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.