Add and use Realm in Android

Source: Internet
Author: User

Add and use Realm in Android

 

Introduction

If you are more concerned about the latest developments in android development, you will certainly have heardRealm, Realm is a lightweight database, which can be replacedSQLiteAndORMFramework.

Compared with SQLite, Realm is faster and has many advanced features, such as JSON support, smooth API, Data Change Notification (observer), encryption support... All of this will make the android Developers more cool (here, how can developers cool, of course, it may be different at home and abroad ...).

The topic of this article is Realm for Android. In this article, I will useRealm v0.84.1.

Add Realm to project

To use Realm in Android projects, you need to add the following code to the module build. gradle file:

compile 'io.realm:realm-android:0.84.1'
Create a Realm

A Realm is similar to SQLite. It has a file associated with it. Once this file is created, it will be permanently stored in the Android system.

To create a Realm, you canActivityCall static methodsRealm.getInstance.

Realm myRealm = Realm.getInstance(context);

It should be noted that we create it like this without specifying itRealmConfigurationAt this time, the created file will use the default file nameDefault. realm.
If you need to create another Realm, you must pass itRealmConfiguration.BuilderAnd you must specify a unique name for it.

Realm myOtherRealm =        Realm.getInstance(                new RealmConfiguration.Builder(context)                        .name(myOtherRealm.realm)                        .build());
Create RealmObject

If a javabean inheritsRealmObjectSo it can be used to store Realm. If you want to know what is javabean, let's take a look at the definition here: javabean is serializable and has a default constructor, the getter and setter methods are provided for all member variables. For example, the following code can be easily saved to Realm,

public class Country extends RealmObject {    private String name;    private int population;    public Country() { }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getPopulation() {        return population;    }    public void setPopulation(int population) {        this.population = population;    }}

Available@PrimaryKeyAnnotation to indicate that this member variable is the primary key of Realm. For example, the following codecodeField as the primary key,

@PrimaryKeyprivate String code;public String getCode() {    return code;}public void setCode(String code) {    this.code = code;}
Create a transaction

In the following code, you will find that using Realm to query data is very simple and it is a little troublesome to write data. Realm follows ACID to ensure atomicity and consistency of operations. In Realm, all write operations are performed in one transaction.

UsebeginTransactionMethod To start a transaction, usecommitTransactionMethod to commit a transaction. The following code shows how to create and saveCountry,

myRealm.beginTransaction();// Create an objectCountry country1 = myRealm.createObject(Country.class); // Set its fieldscountry1.setName(Norway);country1.setPopulation(5165800);country1.setCode(NO);myRealm.commitTransaction();

You may have noticed that,country1The object is not used.CountryCreated by the constructorRealmObjectTo save this instance, you must usecreateObjectMethod.

If you must use the constructor method, do not forget to call it before committing the transaction.copyToRealmMethod to associate objectsRealmFor example:

// Create the objectCountry country2 = new Country();country2.setName(Russia);country2.setPopulation(146430430);country2.setCode(RU);myRealm.beginTransaction();    Country copyOfCountry2 = myRealm.copyToRealm(country2);myRealm.commitTransaction();
Query

Realm provides a set of intuitive and simple APIs for querying operations and callingRealmOfwhereMethod, and pass the class of the class you need into it, you have created a query, and then you can callfindAllMethod to traverse all the data, and the returned data is saved inRealmResultsIn the following example, allCountry

RealmResults
  
    results1 =        myRealm.where(Country.class).findAll();for(Country c:results1) {    Log.d(results1, c.getName());}// Prints Norway, RussiaRealmResults
   
     results1 =        myRealm.where(Country.class).findAll();for(Country c:results1) {    Log.d(results1, c.getName());}// Prints Norway, Russia
   
  

In addition, you can also usebeginsWith,endsWith,lesserThanAndgreaterThanThe following example shows how to usegreaterThanMethod to query allpopulationMore than 0.1 billionCountry,

RealmResults
  
    results2 =        myRealm.where(Country.class)                .greaterThan(population, 100000000)                .findAll();// Gets only Russia
  

You can usefindAllSortedMethod, it has a String type parameter and a boolean type parameter, where, String specifies the field used for sorting, boolean specifies the sorting method,

// Sort by name, RealmResults in descending order
  
   
Results3 = myRealm. where (Country. class). findAllSorted (name, false); // Gets Russia, Norway
  

 

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.