I am trying to get value from my realm db something like this:
public static List<MailData> getAllMailList() {
Realm realm = Realm.getDefaultInstance();
List<MailData> mails = new ArrayList<>();
try {
mails = realm.where(MailData.class)
.sort("receiveDate", Sort.DESCENDING)
.findAll();
return mails;
}catch (Exception e){
e.printStackTrace();
}finally {
realm.close();
}
return mails;
}
or I have tried this approach as well:
try (Realm realm = Realm.getDefaultInstance()) {
return realm.where(MailData.class)
.sort("receiveDate", Sort.DESCENDING)
.findAll();
}
Now, I am calling this in my activity class to read the data like this :
for (MailData data:
getAllMailList()) {
Log.d("Data is:", data.getSubject());
}
While I run the code, showing me this error :
java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.
If i remove realm.close() from finally block, can't delete realm db while logout. Showing me this error :
java.lang.IllegalStateException: It's not allowed to delete the file associated with an open Realm. Remember to close() all the instances of the Realm before deleting its file:
To clear Realm data while logout, code is:
try(Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(realm1 -> {
Realm.deleteRealm(realm1.getConfiguration());
realm1.deleteAll();
});
}catch (Exception e){
e.printStackTrace();
}
So my questions are:
- How to access realm data after closing the realm instance?
- How to delete realm all data while logout?