Removing individual object / row data from Realm in android

I added one user data:

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 one entry from the Realm database, although I tried so hard that it does not work.

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 ideas?

+6
source share
1 answer

You can always find your corresponding one instance RealmResults<UserDatabase>using Realm Queryinstead of the execution cycle for it. try it.

    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 the column name instead.

+16
source

All Articles