2016-11-03 10 views
0

사용을 시작합니다. Realm - 많은 질문이 있습니다. 영역의 새 객체에 primaryKey를 가져 오는 방법은 무엇입니까?

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

가 지금은 새로운 항목을 생성하려면, 영역 - 문서에서이 행 : 그들은 ID 42 설정이 예에서 enter image description here

나는 새 항목을 만들합니다.

그러나 새 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

관련 문제