Navigation

Quick Start

Overview

This page contains information to quickly get Realm Database integrated into your app. Before you begin, ensure you have:

Check Out the Tutorial

This page contains only the essential information that you need to set up a MongoDB Realm application. If you prefer to follow a guided tutorial that shows you step-by-step how to set up a working app, check out the Android Tutorial where you’ll build a mobile app that connects to the Task Tracker backend.

Import Realm

Near the top of any Kotlin file that uses Realm, add the following import statement:

import io.realm.Realm
import io.realm.Realm;

Initialize Realm

Before you can use Realm in your Realm app, you must initialize the Realm library. Your application should initialize Realm just once each time the application runs.

To initialize the Realm library, provide an Android context to the Realm.init() static function. You can provide an Activity, Fragment, or Application context for initialization with no difference in behavior. You can initialize the Realm library in the onCreate() method of an application subclass to ensure that you only initialize Realm once each time the application runs.

Realm.init(this) // context, usually an Activity or Application
Realm.init(this); // context, usually an Activity or Application

Register Your Application Subclass in the Android Manifest

If you create your own Application subclass, you must add it to your application’s AndroidManifest.xml to execute your custom application code. Setting the android.name property of your manifest’s application definition instantiates your Application subclass before any other class when the process for your application is created.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.mongodb.example">

   <application
      android:name=".MyApplicationSubclass"
      ...
   />
</manifest>

Initialize the App

To use MongoDB Realm features such as authentication and sync, you must access your Realm app using your Realm app ID. You can find your Realm app ID in the Realm UI.

val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
      .build())
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

Android Studio Errors?

If Android Studio does not recognize the Realm, App, or AppConfiguration types, there could be a problem with the your Gradle build configuration. To fix the issue, try:

  • Cleaning your project with Build > Clean Project
  • Rebuilding your project based on your updated build.gradle file with Build > Rebuild Project
  • Revisiting the Install the Android SDK guide to make sure that you installed the dependencies correctly.

Define Your Object Model

Your application’s object model controls the data that you can store within Realm Database and synchronize to and from MongoDB Realm.

If have not enabled Realm Sync or you enabled Sync with Development Mode in the Realm UI, you can define your object model directly in code.

Note

If you have enabled Sync but turned off Developer Mode, you can copy and paste the object model definitions that Realm generated for you from the SDKs tab in the Realm UI. You must re-enable Developer Mode if you want to make changes to the object model definition from client side code. See Configure Your Data Model.

import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
import org.bson.types.ObjectId


open class Task(_name: String = "Task", project: String = "My Project") : RealmObject() {
   @PrimaryKey var _id: ObjectId = ObjectId()
   var _partition: String = project
   var name: String = _name

   @Required
   private var status: String = "Open"
}
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
import org.bson.types.ObjectId;

public class Task extends RealmObject {
   @PrimaryKey
   ObjectId _id = new ObjectId();
   String _partition = "My Project";
   String name = "Task";

   @Required
   private String status = "Open";

   public Task(String _name, String project) {
      this._partition = project;
      this.name = _name;
   }

   public Task() {}
}

Authenticate a User

When you have enabled anonymous authentication in the Realm UI, users can immediately log into your app without providing any identifying information:

val credentials: Credentials = Credentials.anonymous()

val user: User? = null
app.loginAsync(credentials) {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully authenticated anonymously.")
         user = app.currentUser()
   } else {
         Log.e(TAG, it.error.toString())
   }
}
Credentials credentials = Credentials.anonymous();

app.loginAsync(credentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated anonymously.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Realm provides many additional ways to authenticate, register, and link users.

Open a Realm

Once you have enabled Realm Sync and authenticated a user, you can open a synced realm. Use the SyncConfiguration to control the specifics of how your application synchronizes data with MongoDB Realm, including the partition, whether to wait for an initial batch of data to sync, and more.

val user: User? = app.currentUser()
val partitionValue: String = "myPartition"
val config = SyncConfiguration.Builder(user!!, partitionValue)
            .waitForInitialRemoteData()
            .build()

var realm: Realm
// Sync all realm changes via a new instance, and when that instance has been successfully created connect it to an on-screen list (a recycler view)
Realm.getInstanceAsync(config, object: Realm.Callback() {
   override fun onSuccess(_realm: Realm) {
      // since this realm should live exactly as long as this activity, assign the realm to a member variable
      realm = _realm
      Log.v(TAG, "Successfully instantiated realm!");
   }
})
// this code assumes the following static member variables:
// static User user;
// static Realm realm;

String partitionValue = "myPartition";
SyncConfiguration config = new SyncConfiguration.Builder(user, partitionValue)
         .waitForInitialRemoteData()
         .build();

// Sync all realm changes via a new instance, and when that instance has been successfully created connect it to an on-screen list (a recycler view)
Realm.getInstanceAsync(config, new Realm.Callback() {
      @Override
      @ParametersAreNonnullByDefault
      public void onSuccess(Realm _realm) {
         // since this realm should live exactly as long as this activity, assign the realm to a member variable
         realm = _realm;
         Log.v(TAG, "Successfully instantiated realm!");
      }
});

See also

Sync Data

Log Out

Once logged in, you can log out:

user?.logOutAsync {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully logged out.")
   } else {
         Log.e(TAG, it.error.toString())
   }
}
user.logOutAsync( it -> {
   if (it.isSuccess()) {
      Log.v(TAG, "Successfully logged out.");
   } else {
      Log.e(TAG, it.getError().toString());
   }
});