Realm 数据库的学习和总结

2018-07-04  本文已影响0人  我就是杨过

Realm数据库简介

配置Realm数据库

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:5.1.0"
    }
}
realm {
  syncEnabled = true;
}

代码中初始化 Realm数据库

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    Realm.init(this);
  }
}

在代码中使用Realm中使用数据库

// Get a Realm instance for this thread           
Realm realm = Realm.getDefaultInstance();    //使用这个方法拿到默认配置的数据库对象

默认配置文件 可以通过 Context.getFilesDir() 可以拿到名为 “ default.realm ”的默认配置文件

// The RealmConfiguration is created using the builder pattern.
// The Realm file will be located in Context.getFilesDir() with name "myrealm.realm"     自定义realm的配置文件名字
RealmConfiguration config = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .encryptionKey(getKey())
  .schemaVersion(42)
  .modules(new MySchemaModule())
  .migration(new MyMigration())
  .build();
// Use the config
Realm realm = Realm.getInstance(config);
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);
RealmConfiguration config = new RealmConfiguration.Builder()
    .assetFile("my.realm")
    .readOnly()
    // It is optional, but recommended to create a module that describes the classes
    // found in your bundled file. Otherwise if your app contains other classes
    // than those found in the file, it will crash when opening the Realm as the
    // schema cannot be updated in read-only mode.
    .modules(new BundledRealmModule())
    .build();
RealmConfiguration myConfig = new RealmConfiguration.Builder()
    .name("myrealm.realm")
    .inMemory()
    .build();

在代码中关闭数据库

 Realm realm = Realm.getDefaultInstance();
        try {
            // ... Use the Realm instance ...
        } finally {
            realm.close();
        }
上一篇 下一篇

猜你喜欢

热点阅读