Laxman Bhattarai Laxman Bhattarai - 6 months ago 228
Android Question

Delete Single Object Data /Row from Realm in android

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

You can always find your matching instance from realm result 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.removeFromRealm();

      realm.commitTransaction();
    }

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