LoginSignup
6
13

More than 5 years have passed since last update.

Android:Realmにおけるauto increment

Posted at

概要

Realmでは、auto increment の機能がサポートされていません。
そのため、auto increment を利用したい場合は、自ら実装する必要があります。
そこで自分なりに実装したものを書いてみました。

auto increment の実装

public class UserDao {
    private Realm mRealm;
    public UserDao(Realm realm) {
        mRealm = realm;
    }

    /**
     * UserのプライマリキーuserIdの最大値をインクリメントした値を取得する。
     * Userが1度も作成されていなければ1を取得する。
     */
    public Integer getNextUserId() {
        // 初期化
        Integer nextUserId = 1;        
        // userIdの最大値を取得
        Number maxUserId = mRealm.where(User.class).max("userId");
        // 1度もデータが作成されていない場合はNULLが返ってくるため、NULLチェックをする
        if(maxUserId != null) {
            nextUserId = maxUserId.intValue() + 1;
        }
        return nextUserId;
    }
}

UserのRealmObjectは以下の形を例に使用しています。

public class User extends RealmObject {

    @PrimaryKey
    private Integer userId = null;
    private String name = null;

    // getter・setterは省略
}

使い方

以下の例では、getNextUserIdメソッドと同じクラス内で使用しています。

public class UserDao {
    // getNextUserIdメソッドなどは省略

    public User createUser(String name) {
        mRealm.beginTransaction();
        User user = realm.createObject(User.class);
        user.setUserId(getNextUserId);
        user.setName(name);
        realm.commitTransaction();
        return user;
    }
}
6
13
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
6
13