ElFrancky
ElFrancky

Reputation: 55

Android Realm how to check if Realm has been initialized

I've a problem with the initialization of Realm. I get systematically an error with :

        Realm realminstance = Realm.getDefaultInstance();

I caught this exception :

No default RealmConfiguration was found. Call setDefaultConfiguration() first

I know I have to init Realm before using it, but could you tell me how can I check if Realm is initialized ? It doesn't works with:

if(Realm.getDefaultConfiguration == null){...}

Thank you very much.

Upvotes: 1

Views: 4010

Answers (2)

Allprod
Allprod

Reputation: 443

You could use a try catch block. I initially initialised my realm in the application class and used it in a content provider and sync adapter but the provider is created before the application apparently so I was forced to do a try catch in all 3 to avoid whatever race condition may occur (couldn't find documentation for what gets created first amongst the components).

`try{
realm = Realm.getDefaultInstance();
} catch (Exception e){
Realm.init()
//Configuration, schema, migration, and encryption details come here
//Now we get the default instance: again.
realm = Realm.getDefaultInstance();
}`

Upvotes: 1

Christian Melchior
Christian Melchior

Reputation: 20126

This code snippet here should work: https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances

// Setup Realm in your Application
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

public class MyActivity extends Activity {
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realm = Realm.getDefaultInstance();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

Upvotes: 1

Related Questions