gpt4 book ai didi

java - Realm 中 ID 的自定义方法以支持自动递增行为

转载 作者:行者123 更新时间:2023-12-01 09:54:58 25 4
gpt4 key购买 nike

我使用 Realm 版本 0.80 一段时间,据我所知,Realm 不支持自动增量行为。
因此,我做了这个解决方法:

public class Item extends RealmObject implements Serializable {

@PrimaryKey
private int id;
private int order;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getOrder() {
return order;
}

public void setOrder(int order) {
id = Increment.Primary_Cart(order); //this line for increment id
this.order = order;
}

这是我增加 id 的静态方法:

public static int Primary_Cart(int id){
if(id>0) {
id_Cart++;
}
return id_Cart;
}

一切工作正常,直到我决定将 Realm 从版本 0.80.0 升级到 0.90.1。
然后我遇到了这个错误:

Caused by: io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 0

更清楚地说,我使用 Realm 解析 JSON,并且某些模型没有 ID,这就是我使用上述解决方法的原因,并且我不想使用其他解决方案,例如 GSON 或其他解决方案。
我需要仅使用 Realm 进行解析和存储,因为我有一个庞大的项目,我想对其进行优化。

最佳答案

现在 Realm 不支持 autoIncrement 功能,但是 carloseduardosx 的要点可能对您有用:https://gist.github.com/carloseduardosx/a7bd88d7337660cd10a2c5dcc580ebd0

这是一个专门为 Realm 数据库实现 autoIncrement 的类。它并不复杂,最相关的部分是这两个方法:

/**
* Search in modelMap for the last saved id from model passed and return the next one
*
* @param clazz Model to search the last id
* @return The next id which can be saved in database for that model,
* {@code null} will be returned when this method is called by reflection
*/
public Integer getNextIdFromModel(Class<? extends RealmObject> clazz) {

if (isValidMethodCall()) {
AtomicInteger modelId = modelMap.get(clazz);
if (modelId == null) {
return 0;
}
return modelId.incrementAndGet();
}
return null;
}

/**
* Utility method to validate if the method is called from reflection,
* in this case is considered a not valid call otherwise is a valid call
*
* @return The boolean which define if the method call is valid or not
*/
private boolean isValidMethodCall() {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for (StackTraceElement stackTraceElement : stackTraceElements) {

if (stackTraceElement.getMethodName().equals("newInstance")) {
return false;
}
}
return true;
}

关于java - Realm 中 ID 的自定义方法以支持自动递增行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37319780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com