gpt4 book ai didi

Java android Realm 检查对象是否存在(检查两个)

转载 作者:行者123 更新时间:2023-11-29 09:47:04 24 4
gpt4 key购买 nike

这是我的对象:

public class ObjectsInGroupRealm extends RealmObject {

@PrimaryKey
private Long id;
private String name;
private String groupName;

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGroupName() {
return groupName;
}

public void setGroupName(String groupName) {
this.groupName = groupName;
}
}

当我创建一个新对象时,我想检查对象是否存在相同的名称和相同的组名。对象名称可以分为几组。这是我如何保存对象的代码:

 public static void saveObjectsInGroup(ArrayList<String> objects, String groupName , Realm realm){

for(String object : objects){

ObjectsInGroupRealm objectsInGroupRealm = new ObjectsInGroupRealm();
Long key;
try {
key = (Long) realm.where(ObjectsInGroupRealm.class).max("id") + 1;
} catch (NullPointerException ex) {
key = 0L; // when there is no object in the database yet
}

objectsInGroupRealm.setId(key);
objectsInGroupRealm.setName(object);
objectsInGroupRealm.setGroupName(groupName);
realm.beginTransaction();
realm.copyToRealm(objectsInGroupRealm);
realm.commitTransaction();
}
}

最佳答案

所以最简单的方法是进行查询并检查返回的对象是否为空:

ObjectsInGroupRealm object = realm.where(ObjectsInGroupRealm.class)
.equalTo("name", name)
.equalTo("groupName", groupName)
.findFirst();
if(object == null){
//add new object
} else {
//handle object already existing
}

关于Java android Realm 检查对象是否存在(检查两个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42620552/

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