I\'m trying to get data from Realm using an ID as a reference. However, when querying for an ID, I\'ve found that Realm is giving me the same ID for all elements (ID of 0).
Here is a genereic solution, personnaly I create a class named RealmUtils and I add this type of methods :
public static int getPrimaryKey(Class c)
{
Realm realm = Realm.getDefaultInstance();
String primaryKeyFied = realm.getSchema().get(c.getSimpleName()).getPrimaryKey();
if (realm.where(c).max(primaryKeyFied)== null)
return 1;
int value = realm.where(c).max(primaryKeyFied).intValue();
return value+1;
}
Why I return 0 when the table is empty ? Because I hate Id's with 0 as value, so just change it. Hope it help someone.
As already mentioned, auto-increment isn't supported yet.
But for those who use kotlin and wants to have an auto-increment behavior with realm, this is one of the possibilities:
open class Route(
@PrimaryKey open var id: Long? = null,
open var total: Double? = null,
open var durationText: String? = null,
open var durationMinutes: Double? = null,
open var distanceText: String? = null,
open var distanceMeters: Int? = null): RealmObject() {
companion object {
@Ignore var cachedNextId:Long? = null
get() {
val nextId = if (field!=null) field?.plus(1)
else Realm.getDefaultInstance()?.where(Route::class.java)?.max("id")?.toLong()?.plus(1) ?: 1
Route.cachedNextId = nextId
return nextId
}
}}
Realm currently doesn't support auto incrementing primary keys. However you can easily implement it yourself using something like:
public int getNextKey() {
try {
Number number = realm.where(object).max("id");
if (number != null) {
return number.intValue() + 1;
} else {
return 0;
}
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
I hope that can get you started.
//generates primary key
public static int getNextKey(RealmQuery realmQuery, String fieldName) {
try {
Number number = realmQuery.max(fieldName);
if (number != null) {
return number.intValue() + 1;
} else {
return 1;
}
} catch (ArrayIndexOutOfBoundsException e) {
return 1;
}
}
Example
int id = RealmDbHelper.getNextKey(realm.where(RealmDocument.class), RealmDocument.FIELD_DOCUMENT_ID)
realmObject.setId(id);
realm.insert(realmObject);
if your Id is Long then:
val nextId = bgRealm.where(Branch::class.java).max("localId") as Long + 1
The Java binding does not support primary keys yet, but it's on the roadmap and with high priority - see: https://groups.google.com/forum/#!topic/realm-java/6hFqdyoH67w . As a workaround you can use this piece of code for generating keys:
int key;
try {
key = realm.where(Child_pages.class).max("id").intValue() + 1;
} catch(ArrayIndexOutOfBoundsException ex) {
key = 0;
}
I use singleton factory for generating primary keys as a more generic solution with better performance (no need to query for max("id")
every time thanks to AtomicInteger
).
There is a long discussion in Realm Git Hub if you need more context: Document how to set an auto increment id?