using this code:
public class App extends Application {
private static App instance;
@Override
public void onCreate() {
super.onCreate();
initRealmDB();
}
private void initRealmDB() {
instance = this;
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().modules(new SimpleRealmModule()).name("RealmSample.realm").build();
Realm realm = null;
try {
realm = Realm.getInstance(realmConfiguration);
realm.setDefaultConfiguration(realmConfiguration);
} finally {
if (realm != null) {
realm.close();
}
}
}
}
**In use:**
Realm realm = Realm.getDefaultInstance();
RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
if(realm.isInTransaction())
{
realm.cancelTransaction();
}
realm.beginTransaction();
if (results != null) {
if(membershipList != null)
{
membershipList.clear();
}
for (int i = 0; i < results.size(); i++) {
Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid());
}
}
Is this best way to use? Should i use singleton approach? If there is another good approach to fulfill this task, please share with me. i followed this https://dzone.com/articles/realm-practical-use-in-android but this code is not working with this dependency: classpath "io.realm:realm-gradle-plugin:3.3.1"
Realm realm = Realm.getInstance(SimpleRealmApp.getInstance());
No
Instead
Realm instances you open with
getInstance()/getDefaultInstance()are thread-local and reference counted, so it is NOT suitable for being used as a singleton across the application. You need to open thread-local instances.So on UI Thread, based on documentation:
For background thread, see the docs:
If you want to use Realm as a singleton, you have to use a class that can increment, decrement, and get instance without incrementing ref count for thread local Realms, kinda like this experiment here.