8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Realmで一意なPrimaryKeyを設定する方法二つ

Last updated at Posted at 2017-03-18

DroidKaigi2017の@zaki50さんによるオフラインファーストなアプリケーション開発より抜粋

@PrimaryKey
public String id = UUID.randomUUID().toString();

この手があったか!っと目から鱗でした。。Contextが取得できる場合ならInstanceID.getInstance(getApplicationContext()).getId();も選択肢にはいるかもしれません。
参照 : 一意の識別子のベストプラクティス

自分でAutoIncrementを書く

Kotlin

inline fun <reified T : RealmObject> getAutoIncrementKey(realm: Realm): Long {
    if (realm.where(T::class.java).count() == 0L) return 1
    else return realm.where(T::class.java).max("id").toLong() + 1
}

// 呼び出し方 getAutoIncrementKey<Dog>(realm)

Kotlin拡張関数

inline fun <reified T : RealmObject> Realm.getAutoIncrementKey(): Long {
    if (where(T::class.java).count() == 0L) return 1
    else return where(T::class.java).max("id").toLong() + 1
}

//呼び出し方 realm.getAutoIncrementKey<Dog>()

Java

public int getAutoIncrementKey(Realm realm, Class klass) {
    if (realm.where(klass).count() == 0) return 1;
    else return realm.where(klass).max("id").intValue() + 1;
}

// 呼び出し方 getAutoIncrementKey(realm, Dog.class)

雑ですが、以上です。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?