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 ?
To delete an object from a realm, use the deleteAllFromRealm() method of the RealmResults instance that contains the objects you would like to delete. You can filter the RealmResults down to a subset of objects using the where() method.
Select a realm and click the Edit button. The Edit Realm wizard displays. Click Next to move to the Realm Objects page where you can click Remove to delete objects from the realm. Click Done.
The right way of deleting your entire Realm (schema) is to use : Realm realm = Realm. getDefaultInstance(); realm. beginTransaction(); // delete all realm objects realm.
To delete all objects from the realm, call Realm. deleteAll() inside of a write transaction. This clears the realm of all object instances but does not affect the realm's schema.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With