Realm (Java) database using the document (Realms)


Realm (Java) database using the document (directory)

Realm is an example of a mobile device database. Realm can be local or synchronized. Realm synchronized use Realm Object Server transparently synchronize their content with other devices. When your App as a local file to continue using synchronous Realm, the Realm of the data may be updated any device with write access to the Realm. In fact, your App can work with the same Realm local or any synchronization.

Whether you want to use a mobile device to synchronize all Realm Realm database?
All documents related to the synchronization has been moved to our platform document

For a more detailed discussion of the Realm, please read the Realm data model .

2.1 Initialization

By instantiating a new Realmopen Realm objects. We've seen in this usage example:

// 初始化Realm
Realm.init(context);

// 获取此线程的Realm实例
Realm realm = Realm.getDefaultInstance();

getDefaultInstance()The method of using the default RealmConfigurationconfiguration example of Realm.

2.1.1 Realm Configuration

To create a controlled way Realm, use RealmConfiguration object. Realm most basic configuration as follows:

RealmConfiguration config = new RealmConfiguration.Builder().build();

This configuration (without options) Use located Context.getFilesDirRealm file default.realm. To use a different configuration, you need to create a new RealmConfigurationtarget:

// 使用构建器模式创建RealmConfiguration。
// Realm文件将位于Context.getFilesDir()中,名称为“ myrealm.realm”
RealmConfiguration config = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .encryptionKey(getKey())
  .schemaVersion(42)
  .modules(new MySchemaModule())
  .migration(new MyMigration())
  .build();
// 使用配置
Realm realm = Realm.getInstance(config);

You can have multiple RealmConfiguration objects, so you can independently control version, architecture and location of each of the Realm.

RealmConfiguration myConfig = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .schemaVersion(2)
  .modules(new MyCustomSchema())
  .build();

RealmConfiguration otherConfig = new RealmConfiguration.Builder()
  .name("otherrealm.realm")
  .schemaVersion(5)
  .modules(new MyOtherSchema())
  .build();

Realm myRealm = Realm.getInstance(myConfig);
Realm otherRealm = Realm.getInstance(otherConfig);

By using Realm.getPathan absolute path to obtain field.

It is important to note that the Realmexample is the thread singleton, which means that the static constructor will return the same instance to respond to all calls from a given thread.

2.2.2 Default Realm

You can RealmConfigurationsave the default configuration. In custom Application settings default class configuration makes it available throughout App.

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    // 默认的Realm文件在Context.getFilesDir();中为“ default.realm”;
    // 我们将其更改为“ myrealm.realm”
    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration.Builder().name("myrealm.realm").build();
    Realm.setDefaultConfiguration(config);
  }
}

public class MyActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Realm realm = Realm.getDefaultInstance(); // 打开“ myrealm.realm”
    try {
      // ... Do something ...
    } finally {
      realm.close();
    }
  }
}

2.2 Opening a synchronized Realm

Whether you want to use a mobile device to synchronize all Realm Realm database?
All documents related to the synchronization has been moved to our platform document

2.3 Read-Only Realms

Read-onlyOnly enforced in the current process. Other processes or devices is still possible to writeRead-onlyRealms. Also, for any write transaction will throw a read-only RealmsIllegalStateException. This includes attempting to write mode, so initially must be provided by other sources.

It comes ready Realm file in your application and sometimes useful - you may want to share some of your data and applications bundled together. In many cases, you do not want to accidentally modify the Realm, purely because the data is read-only. You can bundle Realm file in the assets and use the read-only configuration to do this:

RealmConfiguration config = new RealmConfiguration.Builder()
    .assetFile("my.realm")
    .readOnly()
    // 可选的,但是建议创建一个模块来描述捆绑文件中的类。 否则,如果您的App包含文件中找不到的其他类,则由于无法以只读模式更新架构,因此在打开Realm时它将崩溃。
    .modules(new BundledRealmModule())
    .build();

2.4 Memory Realms

Use inMemoryconfiguration, you can create a rather persistent Realm to disk runs entirely in memory.

RealmConfiguration myConfig = new RealmConfiguration.Builder()
    .name("myrealm.realm")
    .inMemory()
    .build();

If insufficient memory, the memory of the Realm may still use the disk space, but all files created by the memory of the Realm will be deleted when you close the Realm. Allowed to create permanent memory using the same name Realm- Realm names must still be unique.

When all memory Realm instances of a particular name without departing from the scope and reference data will release all the Realm. To keep the memory of the "active" in the course of the execution of the entire application, please keep a reference to it.

2.5 Dynamic Realms - DynamicRealm

In conventional Realmwhen using RealmObjectsubclass definition model class. About the type of security, which has many advantages. But sometimes, these types are available only when running, for example, during migration or CSV file-based data string, you can use DynamicRealm!

DynamicRealm is a variant of the conventional Realm, it can use the data without using the Realm RealmObjectsubclass. But direct use string instead of class to complete all access.

Open the same configuration DynamicRealm using conventional Realm, but DynamicRealm will ignore any configured architecture, migration and schema version.

RealmConfiguration realmConfig = new RealmConfiguration.Builder().build();
DynamicRealm realm = DynamicRealm.getInstance(realmConfig);

// 在DynamicRealm中,所有对象都是DynamicRealmObjects
realm.beginTransaction();
DynamicRealmObject person = realm.createObject("Person");
realm.commitTransaction();

// 使用字符串访问所有字段
String name = person.getString("name");
int age = person.getInt("age");

// 基础架构仍然存在,因此访问不存在的字段将引发异常
person.getString("I don't exist");

// 查询仍然可以正常工作
RealmResults<DynamicRealmObject> persons = realm.where("Person")
    .equalTo("name", "John")
    .findAll();

DynamicRealmAt the expense of flexibility and performance gain flexibility. In general, you should use the conventional Realm. DynamicRealm used only when you need this flexibility.

2.6 Close Realms

RealmImplemented Closeableto process and redistribute native file descriptor memory, and therefore the use of Realm After instance, be sure to close them.

RealmExamples are reference counted - if you call twice in the thread getInstance, you also need two calls close. This allows you to implement Runnablethe class without having to worry about which thread will execute them: just to getInstancethe beginning and to closethe end of the can.

For the UI thread, the easiest way is to have a component onDestroy()execution method realm.close. If you need to create outside the UI Looperthread, you can use the following modes:

public class MyThread extends Thread {

    private Realm realm;

    @Override
    public void run() {
        Looper.prepare();
        realm = Realm.getDefaultInstance();
        try {
            //... 使用Realm实例设置处理程序 ...
            Looper.loop();
        } finally {
            realm.close();
        }
    }
}

For AsyncTask, this is a good model:

protected Void doInBackground(Void... params) {
    Realm realm = Realm.getDefaultInstance();
    try {
        // ... Use the Realm instance ...
    } finally {
        realm.close();
    }

    return null;
}

If you use Threador Runnablefor short-term tasks:

// Run a non-Looper thread with a Realm instance.
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        Realm realm = Realm.getDefaultInstance();
        try {
            // ... Use the Realm instance ...
        } finally {
            realm.close();
        }
    }
});

thread.start();

If you are using minSdkVersion> = 19and Java> = 7the application, you can use the try-with-resources:

try (Realm realm = Realm.getDefaultInstance()) {
    // 无需手动关闭Realm实例
}

2.7 auto-refresh

If from the Looper get Realm instances associated with the thread, the Realm instance will have the auto-refresh function. (Android UI thread is Looper.) This means that the Realm instances will be regularly updated to the latest version. This allows you to effortlessly with the latest content constantly updated UI!

If you have never attach Looperthe thread gets Realm instance, in the call waitForChangebefore the method, the object in this example does not update. Keep the old version of the data is very expensive in terms of memory and disk space, and increases as the number of versions retained between the version and the latest version, the cost will increase. This is why it is very important reason to complete shut down immediately after the Realm instance thread.

To check if your Realm instance activated automatically refresh, use the isAutoRefreshmethod.

Published 59 original articles · won praise 88 · views 190 000 +

Guess you like

Origin blog.csdn.net/geofferysun/article/details/105040333