我添加了单个用户的数据,如下所示:
Realm realm = Realm.getDefaultInstance();
newUser = new UserDatabase();
realm.executeTransaction(new Realm.Transaction() {
public void execute(Realm realm) {
newUser.setClassName(classSectionName);
newUser.setClassNO(classNO);
newUser.setImageUrl(imageUrl);
newUser.setRollNo(rollNO);
newUser.setSchool(school);
// and now saved the data in peresistant data like this:
realm.copyToRealm(newUser);
}
});
但我无法找到从Realm数据库中删除单个条目的方法,即使我尝试过这样做,也无法正常工作。
Realm realm = Realm.getDefaultInstance();
UserDatabase tempUser = new UserDatabase();
final RealmResults<UserDatabase> students = realm.where(UserDatabase.class).findAll();
for(int i=0 ; i<students.size();i++){
final int index =i;
if((students.get(i).getUserID()).equals(prefs.getString(QRActivity.USER_ID_AFTER_LOGIN,"jpt"))&&
(students.get(i).getUserName()).equals(prefs.getString(QRActivity.USER_NAME_AFTER_LOGIN,"jpt"))){
realm.executeTransaction(new Realm.Transaction() {
public void execute(Realm realm) {
//Trying to delete a row from realm.
students.deleteFromRealm(index);
}
});
}
}
有没有人有任何想法?
答案 0 :(得分:16)
您始终可以使用instance
从RealmResults<UserDatabase>
找到匹配的Realm Query
,而不是运行循环。试试这个。
final RealmResults<UserDatabase> students = realm.where(UserDatabase.class).findAll();
UserDatabase userdatabase = students .where().equalTo("userId",prefs.getString(QRActivity.USER_ID_AFTER_LOGIN,"jpt")).equalTo("userName",prefs.getString(QRActivity.USER_NAME_AFTER_LOGIN,"jpt")).findFirst();
if(userdatabase!=null){
if (!realm.isInTransaction())
{
realm.beginTransaction();
}
userdatabase.deleteFromRealm();
realm.commitTransaction();
}
注意: 我只假设您的列中有“userId”和“userName”,您可以改为编写列名。