Delete Single Object Data /Row from Realm in android

erluxman picture erluxman · May 26, 2016 · Viewed 11.5k times · Source

I added a data of single User Like this :

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);
  }
});

But i Could not find a way to delete a single Entry from the Realm Database, even though i tried like this , it is not working .

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);

             }
            });

    }
 }

Does anyone Have any idea ?

Answer

KDeogharkar picture KDeogharkar · May 26, 2016

You can always find your matching instance from RealmResults<UserDatabase> using Realm Query instead of run loop for it . try this.

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();
}

Note : I just assume "userId" and "userName" for your column you can write your column name instead.