This example shows how to initialize an Realm database on Android using Java with init(context) and onCreate() methods.
— Before you can use Realm in your application, you must initialize it.
— This only has to be done once using method Realm.init(context);
— A good place to initialize Realm is in onCreate method of an application subclass.
— If you create your own application subclass, you must add it to the AndroidManifest.xml
AndroidManifest.xml
1 2 3 |
... ... |
MyApplication.java
1 2 3 4 5 6 7 8 9 |
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Realm.init(this); // Initialize Realm } } |
MyActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Realm realm = Realm.getDefaultInstance(); // Get a Realm instance for this thread try { // ... Do something ... } finally { realm.close(); } } } |