Android/Realm

[안드로이드 Realm] Realm에 대하여

정코드 2019. 5. 17. 21:24


Realm 열기


1
2
3
4
5
// Realm 초기화
Realm.init(context);
 
// this 스레드에서 Realm 인스턴스 생성
Realm realm = Realm.getDefaultInstance();
cs



Realm 설정


옵션을 설정하지 않으면 Context.getFilesDir()에 위치한 default.realm를 사용합니다.


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


아래와 같이 설정할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
// RealmConfiguration은 build 패턴을 사용하여 생성합니다.
// Realm 파일 이름을 "myrealm.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);
cs


여러 개의 RealmConfiguration 생성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
cs


Application에서 RealmConfiguration을 기본 설정으로 저장할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    // The default Realm file is "default.realm" in Context.getFilesDir();
    // we'll change it to "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(); // opens "myrealm.realm"
    try {
      // ... Do something ...
    } finally {
      realm.close();
    }
  }
}
cs



읽기 전용 Realm


1
2
3
4
5
6
7
8
9
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();
cs



메모리 영역 Realm


1
2
3
4
5
6
RealmConfiguration myConfig = new RealmConfiguration.Builder()
    .name("myrealm.realm")
    .inMemory()
    // With an in Memory configuration, you can create a Realm
    // that runs entirely in memory without being persisted to disk.
    .build();
cs



동적 Realm


동적 Realm은 RealmObject 클래스를 사용하지 않고 작업할 수있게 해줍니다. 클래스 대신 문자열을 사용합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
RealmConfiguration realmConfig = new RealmConfiguration.Builder().build();
DynamicRealm realm = DynamicRealm.getInstance(realmConfig);
 
// 동적 Realm의 모든 객체는 DynamicRealmObjects 입니다.
realm.beginTransaction();
DynamicRealmObject person = realm.createObject("Person");
realm.commitTransaction();
 
// 모든 field는 문자열로 접근합니다.
String name = person.getString("name");
int age = person.getInt("age");
 
// 존재하지 않는 field에 접근하면 예외가 발생합니다.
person.getString("I don't exist");
 
// 쿼리도 가능합니다.
RealmResults<DynamicRealmObject> persons = realm.where("Person")
    .equalTo("name""John")
    .findAll();
cs



Realm 닫기


파일 기술자 및 메모리 할당 해제를 위해 항상 Realm을 닫아야 합니다. Realm 인스턴스를 두 번 호출했다면 close를 두 번 호출해야 합니다. UI 스레드인 경우 onDestroy에서 close를 실행하면 됩니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MyThread extends Thread {
 
    private Realm realm;
 
    @Override
    public void run() {
        Looper.prepare();
        realm = Realm.getDefaultInstance();
        try {
            //... Setup the handlers using the Realm instance ...
            Looper.loop();
        } finally {
            realm.close();
        }
    }
}
cs


AsyncTask의 경우


1
2
3
4
5
6
7
8
9
10
protected Void doInBackground(Void... params) {
    Realm realm = Realm.getDefaultInstance();
    try {
        // ... Use the Realm instance ...
    } finally {
        realm.close();
    }
 
    return null;
}
cs


Thread 또는 Runnable의 경우


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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();
cs


minSdkVersion >= 19, Java >= 7의 경우


1
2
3
try (Realm realm = Realm.getDefaultInstance()) {
    // No need to close the Realm instance manually
}
cs



자동 새로고침


Looper와 관련된 스레드에서 Realm 인스턴스를 생성하면 자동으로 최신 버전으로 업데이트 됩니다.

Looper가 연결되지 않은 스레드에서 Realm 인스턴스를 생성하면 waitForChange를 호출하기 전까지는 업데이트되지 않습니다.

isAutoRefresh를 사용하여 자동 새로고침이 활성화되었는지 확인할 수 있습니다.




출처


https://realm.io/docs/java/latest#realms