我使用领域版本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 然后我有这个错误:
引起:io.realm.exceptions.RealmPrimaryKeyConstraintException: 值已存在:0
为了更清楚,我使用Realm解析JSON,有些模型没有ID,这就是我使用上述解决方法的原因,我不想使用像GSON这样的其他解决方案。
我只需要使用Realm进行解析和存储,因为我有一个庞大的项目,我想要优化它。
答案 0 :(得分:1)
现在Realm不支持autoIncrement功能,但carloseduardosx的这个要点可能对您有用:https://gist.github.com/carloseduardosx/a7bd88d7337660cd10a2c5dcc580ebd0
这是一个专门针对Realm数据库的类whick实现autoIncrement。它并不复杂,mosr相关部分是这两种方法:
/**
* 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;
}