Realm and auto increment Behavior (Android)

后端 未结 8 2110
野的像风
野的像风 2020-12-14 16:22

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).

8条回答
  •  粉色の甜心
    2020-12-14 16:54

    Sadly, I can't comment on other answers, but I'd like to add to Vinicius` answer.

    First, you shouldn't open a new realm instance, when looking for primary key, especially when you don't close them, as this adds to maximum possible file descriptor count.

    Secondly, although this is a preference, you shouldn't have primitive types (or object equivalents) as nullables (in Kotlin), as this adds redundant requirement to check nullability.

    Third, since you're using kotlin, you can just define an extension method to Realm class, such as:

    fun Realm.getNextId(model: RealmModel, idField : String) : Long
    {
        val count = realm.where(model::class.java).max(idField)
        return count + 1L
    }
    

    Since all RealmObject instances are RealmModel, and even objects that aren't tracked by Realm are still RealmModel instances, therefore it will be available where ever you use your realm related classes. Java equivalent would be:

    static long getNextId(RealmModel object, Realm realm, String idField)
    {
        long count = realm.where(object.class).max(idField);
        return count + 1;
    }
    

    Late edit note: You're better off not using this approach if you're dealing with data that might come from outside sources, such as other databases or the web, because that WILL result in collisions between data in your internal database. Instead you should use max([id field name]). See the previous snippets, I already modified them to accommodate for this edit.

提交回复
热议问题