Realm get instance as thread


(Omar Othman) #1

i was tired to find realm.getDefaultInstance or getInstance as thread

let we say we have 2 classes is working on background to get message from server

and when i use realm from some class to save message:

Realm.init(context);
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
// save all data
realm.commitTransaction();
realm.close();

and when i use adapter to load items from realm

application load data very slow and sometime i get: application did’t response

load data from realm code:

new Thread(() -> {
  list.clear();
  Realm.init(context);
  Realm realm = Realm.getInstance(MoonApplication.group);
  RealmResults chats = realm.where(MessageRoom.class).equalTo("from", username).and().equalTo("to", us).or().equalTo("from", us).and().equalTo("to", username).findAll();
  if(chats != null){
     for(int i=0; i<chats.size(); i++){
        long id = chats.get(i).getId();
        String from = chats.get(i).getFrom();
        String to = chats.get(i).getTo();
        String body = chats.get(i).getBody();
        String time = chats.get(i).getTime();
        // etc.....
    }
  }
  realm.close();
  ((Activity)context).runOnUiThread(this::notifyDataSetChanged);
}).start();

Note: when i close realm from some class it’s closed from all classes and if i not close it, i get notification by log, are you forget to close realm?

can someone tell me how to use best way to load and save data on realm?

Thanks for help!