2016-11-03 5 views
0

私は使用を開始するRealm - 私は多くの質問があります。私は新しいアイテムを作成したいレルムの新しいオブジェクトのprimaryKeyを取得する方法は?

:彼らはIDの42を設定し、この例では enter image description here

class Item extends RealmObject { 
    @PrimaryKey 
    int id; 
    // ... 
} 

は、今私は、レルム・ドキュメントからこの行を新しい項目を作成します。

しかし新しいItemオブジェクトでPrimaryKeyの実際の値を取得するにはどうすればよいですか?

答えて

0
public int getNextPrimaryKey(RealmObject ob) { // ob extneds RealmObject 
    int primaryKey = 1; 
    try { 
     primaryKey = realm.where(ob.getClass()).max(Constants.ID).intValue() + 1; 
    } catch (Exception e) { 
     // if table for this item is empty 
    } 
    return primaryKey; 
} 
+1

これは機能します。これはより効率的です:https://github.com/realm/realm-java/issues/469#issuecomment-182897019その問題には他にも提案があります。 –

+0

何らかの理由で私が*自動インクリメントIDを必要とする新しいプロジェクトを作成した場合、原子的な整数を設定するのは面倒です。代わりにこのソリューションを使用します(トランザクションで)。 – EpicPandaForce

関連する問題