Android Database Realm Practice

Source: Internet
Author: User

There are 5 commonly used databases in Android development:

1. OrmliteOrmlite is not a dedicated ORM framework for the Android platform, it is a Java ORM. Supports JDBC connection, spring and Android platform. Annotations (Annotation) are widely used in the syntax.

2. SugarormSugarorm is a dedicated ORM for the Android platform. Provide easy-to-learn APIs. It is easy to process 1 pairs of 1 and 1-to-many relational data and simplify CRUD basic operations with 3 functions, save (), delete (), and find () (or FindByID ()).

3. Greendaowhen performance is important (data access is frequent), Greendao is a quick solution that can support thousands of records of crud per second, and Ormlite is almost 4.5 times times faster than Greendao. (Please benchmark the exact data).

Greendao is less than 100KB, so it has little effect on the size of the app apk.

4. Active AndroidActive Record (Active Directory) is a typical way of naming ORM implementations in frameworks such as Yii, rails, and so on. Active Android helps you manipulate SQLite in an object-oriented way.
To include active Android in your project, you need to add a jar file under the project's/libs directory. You can get the source code from GitHub and edit it using Maven.

5. RealmRealm is a ready-to-use Android ORM that is written in C + + and runs directly on your device hardware (no need to be interpreted), so it runs quickly. It is also open source cross-platform, iOS code can be found on GitHub, you can also find objective C and swift written realm usages.


Faster than Sqlite,realm and has many modern database features, such as support for JSON, streaming APIs, data change notifications, and encryption support, are all handy for Android developers.

Ream provides five ways to implement the programming. Java,objective C,swift,react-native,tamarin, respectively. Here I focus on the use of Android.

You can read the official documentation directly, and I'll explain it on this basis: Realm uses


Quick Start :

Operating Environment
    • Currently we do not support the Java environment other than Android;
    • Android Studio >= 1.5.1;
    • Newer version of the Android SDK;
    • JDK version >=7;
    • We support Android API for all versions above 9 (Android 2.3 Gingerbread and above).
Building dependency Relationships

first step:   Add the following class path dependency in the project's Build.gradle file.

buildscript  { repositories  { jcenter   ()  }  dependencies   { classpath  " io.realm:realm-gradle-plugin:1.0.0 " }  }  

 build.gradle   file in the following location:

Step two:   apply Build.gradle  realm-android   plugins.

apply  plugin:   ' realm-android '    

The app's build.gradle files are in the following location:

If the reader is using a MAVEN build project, it's official, and I'm not going to list it here.

Speaking of which, we can't wait to try.

1,application inside initialization

public class Realmapplication extends application {    @Override public    void OnCreate () {        super.oncreate ();        Init ();    }    private void Init () {        realmconfiguration realmconfiguration = new Realmconfiguration.builder (this). build ();        Realm.setdefaultconfiguration (realmconfiguration);    }}

2, create Tools management class, Get realm instance

public class Realmutils {    private static  realmutils instance;    Public final Context Mcontext;    Private String Realmname = "Realm_demo.realm";    Public realmutils (Context mcontext) {        this.mcontext = mcontext;    }    Public  static  realmutils getinstance (context context) {        if (instance = = null) {            synchronized ( Realmutils.class) {                if (instance = = null) {                    instance = new Realmutils (context);}}        }        return  instance;    }    Public  Realm Getrealm () {        Realm Realm =realm.getinstance (new Realmconfiguration.builder (Mcontext). Name ( Realmname). Build ());        return  realm;    }}
3, create a Realmobject object that stores object

For example, we now need to store a person object, and notice that the member properties here are written in private for the realm's serialization.


public class Person extends Realmobject {    @PrimaryKey    private string code;//number    private string name;//name    private int age;//age public Person    () {    } public person    (int age, string code, string name) {        This.age = age;        This.code = code;        this.name = name;    }    Public String GetCode () {        return code;    }    public void Setcode (String code) {        this.code = code;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    public int getage () {        return age;    }    public void Setage (int.) {        this.age = age;    }    @Override public    String toString () {        return "person{" +                "code= '" + code + ' \ ' +                ", name= ' + name + ' \ ' + '                , age= "+ Age +                '} ';}    }

4, define a few crud methods for other classes to implement

Public interface Persondao {    //inserting    void Insert (person person) throws Exception;    Query    list<person> Getallperson () throws Exception;    Update person    Updateperson (person person) throws Exception;    Delete    void Deleteperson (String code) throws Exception;    asynchronously inserts a    void Insertpersonasync (person person) throws Exception;}
5, the concrete implementation of the object

public class Persondaoimpl implements Persondao {private context context;    Private Realm Mrealm;    Public Persondaoimpl (Context context) {Mrealm = realmutils.getinstance (context). Getrealm ();        } @Override public void Insert (person person) throws Exception {mrealm.begintransaction ();        Person Person1 = Mrealm.copytorealm (person);        Mrealm.committransaction ();    Mrealm.close ();        } @Override Public list<person> Getallperson () throws Exception {list<person> mlist = null;        Mlist = Mrealm.where (Person.class). FindAll ();        Mrealm.close ();    return mlist;        } @Override Public person Updateperson (person person) throws Exception {mrealm.begintransaction ();        Person Person1 = mrealm.copytorealmorupdate (person);        Mrealm.committransaction ();        Mrealm.close ();    return person1; } @Override public void Deleteperson (String code) throws Exception {person person = Mrealm.where (Person.class). Equalto ("code", Code). FindFirst ();        Mrealm.begintransaction ();        Person.deletefromrealm ();    Mrealm.committransaction (); } @Override public void Insertpersonasync (Final man person) throws Exception {//A realm can only be accessed in the same thread, in a child thread The row database operation must regain the Realm object: Mrealm.executetransaction (New Realm.transaction () {@Override public voi                D Execute (Realm realm) {realm.begintransaction ();                Person Person1 = Realm.copytorealm (person);                Realm.committransaction ();            Realm.close ();//And remember to close realm.close () when you leave the thread;        }        });    Close Realm Object Mrealm.close (); }}

6, Test

public class Mainactivity extends Appcompatactivity {    private Realm Mrealm;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Init ();    }    private void Init () {person person        = new person ();        Person.setname ("test");        Person.setage (+);        Person.setcode ("xxxx");        Persondao dao = new Persondaoimpl (this);        try {            //increase            dao.insert (person);             Query all            Dao.getallperson ();            Specify code Delete            Dao.deleteperson ("xxxx");            Update            Dao.updateperson (person),        } catch (Exception e) {            e.printstacktrace ();}}    }

In fact, this is similar to the previous usage, a bit is that realm to help us manage this database, and in the security I have not mentioned, here is only the basic usage, you can go to see the Official document Description:

Official documents


Android Database Realm Practice

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.