This example shows how to configure a Realm Database on Android using default configuration with Java RealmConfiguration class and get the instance of realm thread.
— A Realm is an instance of a Realm Mobile Database container.
— Default Realm configuration uses the Realm file “default.realm” located in Context.getFilesDir().
— To use another configuration, you would create a new RealmConfiguration object.
— The RealmConfiguration can be saved as a default configuration.
— Setting a default configuration in your custom Application class makes it available in rest of your code.
AndroidManifest.xml
1 2 3 |
... ... |
MyApplication.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Realm.init(this); // Initialize Realm // The RealmConfiguration is created using the builder pattern. // The Realm file will be located in Context.getFilesDir() with name "myapp.realm" RealmConfiguration config = new RealmConfiguration.Builder() .name("myapp.realm") .encryptionKey(getKey()) .schemaVersion(6) .build(); Realm.setDefaultConfiguration(config); } } |
MyActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get a Realm instance for this thread. opens "myapp.realm". Realm realm = Realm.getDefaultInstance(); try { // ... Do something ... } finally { realm.close(); } } } |