Realm and auto increment Behavior (Android)

后端 未结 8 2136
野的像风
野的像风 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:38

    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
            }
    }}
    

提交回复
热议问题