Mysql > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm with Application > create a Realm




Add or delete check









Asynchronous delete

Demo address: github.com/RaphetS/Dem…

Introduction to Realm

Database Realm is an alternative to SQLite. It has its own database storage engine that is lighter and faster than SQLite, with many of the features of modern databases, such as JSON support, streaming apis, data change notification, automatic data synchronization, simple authentication, access control, Event processing, the most important is cross-platform, there are currently Java, Objective C, Swift, React-Native, Xamarin five implementations.

Version used for this article is Realm 2.0.2(official documentation)

Two, environment configuration

(1) Add to the build file of the project

Buildscript {repositories {jCenter ()} dependencies {classpath "IO. Realm :realm-gradle-plugin:2.0.2"}}Copy the code

(2) Add it to the build file of app

apply plugin: 'realm-android'Copy the code

Initialize the Realm

Realm.init() in Application onCreate ()
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Realm.init(this); }}Copy the code
(2) Configure a Realm in the Application onCreate () method

① Use the default Settings

public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // The Realm file will be located in Context.getFilesDir() with name "default.realm" Realm.init(this); RealmConfiguration config = new RealmConfiguration.Builder().build(); Realm.setDefaultConfiguration(config); }}Copy the code

② Use custom configuration

public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Realm.init(this); RealmConfiguration config = new RealmConfiguration.Builder() .name("myRealm.realm") .deleteRealmIfMigrationNeeded() .build(); Realm.setDefaultConfiguration(config); }}Copy the code
(3) Configure the custom Application in Androidmanifest.xml
Copy the code

4. Create entities

(1) Create a new class that extends RealmObject
public class Dog extends RealmObject { private String name; private int age; @PrimaryKey private String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; }}Copy the code

Many-to-many relationships:

public class Contact extends RealmObject {
    public String name;
    public RealmList emails;
}

public class Email extends RealmObject {
    public String address;
    public boolean active;
}Copy the code
(2) Other relevant instructions

1. Supported data types: Boolean, byte, short, int, long, float, double, String, Date and byte[] In Realm byte, short, int, long are all mapped to type long

2. Notes

The @primaryKey ① field must be String, INTEGER, byte, short, int, long and their encapsulation classes Byte, short, INTEGER, and Long

② After using this annotation, you can use the copyToRealmOrUpdate() method to query its object by primary key, if found, update it, otherwise create a new object instead.

③ The @index annotation is set by default if this annotation is used

④ With this annotation, creating and updating data will be slower, and querying data will be faster.

@required Data cannot be null

@ignore Indicates that the field is not stored locally

@index adds a search engine to the field, which makes the insertion slower and the data larger, but the query faster. It is recommended to optimize read performance.

Five,

(1) Implementation method 1: transaction operation
Type 1: Create an object and store itCopy the code
Realm realm=Realm.getDefaultInstance();

realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("[email protected]");
realm.commitTransaction();Copy the code
Type 2: Copy an object to a Realm databaseCopy the code
Realm realm=Realm.getDefaultInstance();

User user = new User("John");
user.setEmail("[email protected]");

// Copy the object to Realm. Any further changes must happen on realmUser
realm.beginTransaction();
realm.copyToRealm(user);
realm.commitTransaction();Copy the code
(2) Implementation method two: use transaction block
Realm mRealm=Realm.getDefaultInstance(); final User user = new User("John"); user.setEmail("[email protected]"); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealm(user); }});Copy the code

Six, delete

Realm mRealm=Realm.getDefaultInstance(); final RealmResults dogs= mRealm.where(Dog.class).findAll(); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Dog dog=dogs.get(5); dog.deleteFromRealm(); / / remove the first data dogs. DeleteFirstFromRealm (); // Delete the last data.dogs.deletElastFromrealm (); // Delete data dog.deleteFromrealm (1); // Delete data dog.deleteFromrealm (1); // Delete all data dog.deleteAllFromrealm (); }});Copy the code

You can also delete them using beginTransaction and commitTransaction methods as above

Seven,

Realm  mRealm=Realm.getDefaultInstance();

Dog dog = mRealm.where(Dog.class).equalTo("id", id).findFirst();
mRealm.beginTransaction();
dog.setName(newName);
mRealm.commitTransaction();Copy the code

It is also possible to update data with transaction blocks

Eight,

(1) Query all

The result of the query is RealmResults, which can be converted to a List using the mrealm.copyfromrealm (Dogs) method

    public List queryAllDog() {
        Realm  mRealm=Realm.getDefaultInstance();

        RealmResults dogs = mRealm.where(Dog.class).findAll();

        return mRealm.copyFromRealm(dogs);
    }Copy the code
(2) Conditional query
    public Dog queryDogById(String id) {
        Realm  mRealm=Realm.getDefaultInstance();

        Dog dog = mRealm.where(Dog.class).equalTo("id", id).findFirst();
        return dog;
    }Copy the code

Common conditions are as follows (please check the official documentation for details) :

  • between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()

  • equalTo() & notEqualTo()

  • contains(), beginsWith() & endsWith()

  • isNull() & isNotNull()

  • isEmpty() & isNotEmpty()

(3) Sort the query results
/** * query (query all) */ public List queryAllDog() {RealmResults dogs = mRealm. Where (dog.class).findAll(); /** * sort =dogs.sort(" Id "); DESCENDING =dogs. Sort ("id", sort.DESCENDING); return mRealm.copyFromRealm(dogs); }Copy the code
(4) Other queries

Sum, min, Max, and Average support only integer data fields

Private void getAverageAge() {double avgAge= mRealm. Where (dog.class).findall ().average("age"); Private void getSumAge() {Number sum= mRealm. Where (dog.class).findAll().sum("age"); int sumAge=sum.intValue(); Private void getMaxId(){Number Max = mRealm. Where (dog.class).findall ().max("age"); int maxAge=max.intValue(); }Copy the code

9. Asynchronous operation

In most cases, the add, delete, alter, and query operations on a Realm are fast enough to be performed in a UI thread. However, in the case of complicated add, delete, change, or query operations, or a large amount of data, the sub-thread can perform the operation.

(1) Asynchronous increase:
private void addCat(final Cat cat) { RealmAsyncTask addTask= mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealm(cat); }}, a new Realm. Transaction. OnSuccess () {@ Override public void OnSuccess () {ToastUtil. ShowShortToast (mContext, "collection of success"); }}, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { ToastUtil. ShowShortToast (mContext," Collection failed "); }}); }Copy the code

Finally, when destroying an Activity or Fragment, cancel the asynchronous task

@Override protected void onDestroy() { super.onDestroy(); if (addTask! =null&&! addTask.isCancelled()){ addTask.cancel(); }}Copy the code
(2) Asynchronous deletion
private void deleteCat(final String id, final ImageView imageView){ RealmAsyncTask deleteTask= mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Cat cat=realm.where(Cat.class).equalTo("id",id).findFirst(); cat.deleteFromRealm(); }}, The new Realm. Transaction. OnSuccess () {@ Override public void OnSuccess () {ToastUtil. ShowShortToast (mContext, cancel the collection "success"); }}, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { ToastUtil. ShowShortToast (mContext," unbookmark failed "); }}); }Copy the code

Finally, when destroying an Activity or Fragment, cancel the asynchronous task

@Override protected void onDestroy() { super.onDestroy(); if (deleteTask! =null&&! addTask.isCancelled()){ deleteTask.cancel(); }}Copy the code
(3) asynchronous change
RealmAsyncTask updateTask= mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Cat cat=realm.where(Cat.class).equalTo("id",mId).findFirst(); cat.setName(name); }}, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { ToastUtil. ShowShortToast (UpdateCatActivity. This," UpdateCatActivity successfully "); }}, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { ToastUtil. ShowShortToast (UpdateCatActivity. This," Failed and succeeded "); }});Copy the code

Finally, when destroying an Activity or Fragment, cancel the asynchronous task

@Override protected void onDestroy() { super.onDestroy(); if (updateTask! =null&&! addTask.isCancelled()){ updateTask.cancel(); }}Copy the code
(4) Asynchronous search
RealmResults cats=mRealm.where(Cat.class).findAllAsync(); cats.addChangeListener(new RealmChangeListener>() { @Override public void onChange(RealmResults element) { element= element.sort("id"); List datas=mRealm.copyFromRealm(element); }});Copy the code

Finally, when destroying an Activity or Fragment, cancel the asynchronous task

 @Override
    protected void onDestroy() {
        super.onDestroy();
        cats.removeChangeListeners();

    }Copy the code

Ten, finally

I spent nearly a week writing this article and Demo, hoping to be helpful to you. If you have any questions, welcome to put forward, learn together, progress together. Demo is based on the local collection as the application scenario, the realization of the add, delete, change, check and other operations, as well as asynchronous add, delete, change and check operations, the process also step on a lot of pits. The Demo experience:




demo.png

Demo address: github.com/RaphetS/Dem… Welcome Star and Fork.