领域和自动增量行为(Android) [英] Realm and auto increment Behavior (Android)

查看:83
本文介绍了领域和自动增量行为(Android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ID作为参考从Realm获取数据。但是,在查询ID时,我发现Realm为所有元素(ID为0)提供了相同的ID。当我在模型的ID上使用 @PrimaryKey 注释时,为什么ID不会自动增加?

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). Why doesn't the ID auto-increment when I use the @PrimaryKey annotation on the model's ID?

这里是模型的缩短类:

public class Child_pages extends RealmObject {
    @PrimaryKey
    private int id_cp;

    private int id;
    private String day;
    private int category_id;

我正在执行的查询是: realm.where(Child_pages。 class).equalTo(id_cp,page_id).findFirst()

And the query I'm executing is: realm.where(Child_pages.class).equalTo("id_cp",page_id).findFirst()

推荐答案

Realm目前还没有不支持自动递增主键。但是你可以使用类似的东西轻松地实现它:

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

我希望能帮到你。

这篇关于领域和自动增量行为(Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆