Reputation: 1460
I have a configuration class within my Android application that I store within a Realm database. I just edited it to follow the singleton design pattern so there is only ever once instance of the configuration.
The problem is, the class now has a private constructor to prevent instantiation without calling my 'getInstance' method. However, RealmObject seems to require a public constructor.
Is it not possible to have a class that extends RealmObject using a singleton design pattern?
Is this simply a limitation of Realm that I am going to have to account for?
Here is a snippet of code for context:
public static AppConfiguration getInstance(){
if(configuration == null){
synchronized (AppConfiguration.class) {
if (configuration == null) {
configuration = new AppConfiguration();
}
}
}
return configuration;
}
//constructor is private to prevent instantiation without using getInstance, enforces singleton
private AppConfiguration() { //The constructor defined as private which is causing the problem
this.isRegistered = false;
this.isLoggedIn = false;
}
Upvotes: 0
Views: 634
Reputation: 81588
Conceptually your singleton setup does not make sense in the context of Realm, because you synchronize an unmanaged object (thus allowing "only one thread to access it at once" via mutual exclusion / locking), which brings up the question:
RealmObject
? (Realm allows consistency with its MVCC architecture, if you use a detached copy then why use Realm at all for its persistence?)But yes, you need a public constructor for RealmObject so that Realm can instantiate its proxy instances. Perhaps you can try a protected
constructor, and see if the RealmProxy can be instantiated via reflection if you do that.
Upvotes: 1