Bac*_*ime 26 java android realm
我正在尝试使用ID作为参考从Realm获取数据.但是,在查询ID时,我发现Realm为所有元素(ID为0)提供了相同的ID.当我@PrimaryKey在模型的ID上使用注释时,为什么ID不会自动递增?
这是模型的缩短类:
public class Child_pages extends RealmObject {
@PrimaryKey
private int id_cp;
private int id;
private String day;
private int category_id;
Run Code Online (Sandbox Code Playgroud)
我正在执行的查询是: realm.where(Child_pages.class).equalTo("id_cp",page_id).findFirst()
Bac*_*ime 65
Realm目前不支持自动递增主键.但是,您可以使用以下内容轻松实现它:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能让你开始.
zac*_*usz 10
Java绑定尚不支持主键,但它位于路线图上且具有高优先级 - 请参阅:https://groups.google.com/forum/# !topic / last-java/6hFqdyoH67w.作为一种解决方法,您可以使用这段代码生成密钥:
int key;
try {
key = realm.where(Child_pages.class).max("id").intValue() + 1;
} catch(ArrayIndexOutOfBoundsException ex) {
key = 0;
}
Run Code Online (Sandbox Code Playgroud)
我使用singleton工厂生成主键作为更通用的解决方案,具有更好的性能(不需要max("id")每次都查询AtomicInteger).
如果您需要更多上下文,Realm Git Hub中有一个长时间的讨论:记录如何设置自动增量ID?
| 归档时间: |
|
| 查看次数: |
20452 次 |
| 最近记录: |