You are reading the documentation for an older version of Realm. You can view the latest documentation instead.

Getting started

Download Realm for Android

Or, download the source for realm-java on GitHub.

Realm Java lets you efficiently write your app’s model layer in a safe, persistent, and fast way. Here’s what it looks like:

// Define your model class by extending RealmObject
public class Dog extends RealmObject {
    private String name;
    private int age;

    // ... Generated getters and setters ...
}

public class Person extends RealmObject {
    @PrimaryKey
    private long id;
    private String name;
    private RealmList<Dog> dogs; // Declare one-to-many relationships

    // ... Generated getters and setters ...
}

// Use them like regular java objects
Dog dog = new Dog();
dog.setName("Rex");
dog.setAge(1);

// Initialize Realm (just once per application)
Realm.init(context);

// Get a Realm instance for this thread
Realm realm = Realm.getDefaultInstance();

// Query Realm for all dogs younger than 2 years old
final RealmResults<Dog> puppies = realm.where(Dog.class).lessThan("age", 2).findAll();
puppies.size(); // => 0 because no dogs have been added to the Realm yet

// Persist your data in a transaction
realm.beginTransaction();
final Dog managedDog = realm.copyToRealm(dog); // Persist unmanaged objects
Person person = realm.createObject(Person.class); // Create managed objects directly
person.getDogs().add(managedDog);
realm.commitTransaction();

// Listeners will be notified when data changes
puppies.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<Dog>>() {
    @Override
    public void onChange(RealmResults<Dog> results, OrderedCollectionChangeSet changeSet) {
        // Query results are updated in real time with fine grained notifications.
        changeSet.getInsertions(); // => [0] is added.
    }
});

// Asynchronously update objects on a background thread
realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm bgRealm) {
        Dog dog = bgRealm.where(Dog.class).equalTo("age", 1).findFirst();
        dog.setAge(3);
    }
}, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {
        // Original queries and Realm objects are automatically updated.
        puppies.size(); // => 0 because there are no more puppies younger than 2 years old
        managedDog.getAge();   // => 3 the dogs age is updated
    }
});

Prerequisites

  • Android Studio version 1.5.1 or higher
  • JDK version 7.0 or higher
  • A recent version of the Android SDK
  • Android API Level 9 or higher (Android 2.3 and above)

Note: Realm does not support Java outside of Android. We no longer support Eclipse as an IDE; please migrate to Android Studio.

Installation

Install Realm as a Gradle plugin.

Step 1: Add the class path dependency to the project level build.gradle file.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:3.7.1"
    }
}

Find the project level build.gradle file here:

Project level build.gradle file

Step 2: Apply the realm-android plugin to the top of the application level build.gradle file.

apply plugin: 'realm-android'

Find the application level build.gradle file here:

Application level build.gradle file

Once you make these two changes, simply refresh your gradle dependencies. If you’re upgrading from a version of Realm earlier than v0.88, you may also need to clean your gradle project (./gradlew clean).

Find a sample of the two modified build.gradle files here:

Enabling Realm Mobile Platform: Before your application can synchronize with the Realm Object Server, it has to be enabled in your build file. Add this to the application’s build.gradle:

realm {
  syncEnabled = true;
}

Other Build Systems

The Maven & Ant build systems are not supported. We’re tracking interest in supporting them on GitHub:

A ProGuard configuration is provided as part of the Realm library. This means that you don’t need to add any Realm specific rules to your ProGuard configuration.

Realm Browser

You can use the standalone Realm Browser Mac application to read and edit .realm databases. (You can also download it from GitHub.)

Realm Browser

Create a test database with sample data using the menu item Tools > Generate demo database.

If you need help finding your app’s Realm file, check this StackOverflow answer for detailed instructions.

The browser is macOS-only. While we’re working on a web-based Realm Browser, right now you can use the Stetho-Realm plugin for Stetho, an Android debug bridge for the Chrome browser created by Facebook.

Examples

Take a look at our examples to see Realm used in practice in an app. See here for more details on how to run the examples.

The introExample contains simple examples of how you use the Realm API.

The gridViewExample is a trivial app that shows how to use Realm as the backing store for a GridView. It also shows how you could populate the database with JSON using GSON plus how to use ABI splits to minimize the size of the final APK.

The threadExample is a simple app that shows how to use Realm in a multithreaded environment.

The adapterExample shows how to use the RealmBaseAdapter and RealmRecyclerViewAdapter to make Realm work with Android ListView and RecyclerView in an elegant way.

The jsonExample demonstrates Realm’s JSON facilities.

The encryptionExample shows you how to work with encrypted Realms.

The rxJavaExamples shows how Realm works together with RxJava.

The unitTestExample shows how you can write unit tests when working with Realm.

Initializing Realm

Before you can use Realm in your app, you must initialize it. This only has to be done once.

Realm.init(context);

You must provide an Android context. A good place to initialize Realm is in onCreate on an application subclass:

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    Realm.init(this);
  }
}

If you create your own application subclass, you must add it to the app’s AndroidManifest.xml:

<application
  android:name=".MyApplication"
  ...
/>

Realms

A Realm is an instance of a Realm Mobile Database container. Realms can be local or synchronized. A synchronized Realm uses the Realm Object Server to transparently synchronize its contents with other devices. While your application continues working with a synchronized Realm as if it’s a local file, the data in that Realm might be updated by any device with write access to that Realm. In practice, your application works with any Realm, local or synchronized, the same way, although opening a synchronized Realm requires a User that’s been authenticated to the Object Server and that’s authorized to open that Realm.

For a more detailed discussion about Realms, read The Realm Data Model.

Opening Realms

Open a Realm by instantiating a new Realm object. We’ve seen this used already in examples:

// Initialize Realm
Realm.init(context);

// Get a Realm instance for this thread
Realm realm = Realm.getDefaultInstance();

The getDefaultInstance method instantiates the Realm with a default RealmConfiguration.

Configuring a Realm

To control how Realms are created, use a RealmConfiguration object. The minimal configuration usable by Realm is:

RealmConfiguration config = new RealmConfiguration.Builder().build();

That configuration—with no options—uses the Realm file default.realm located in Context.getFilesDir. To use another configuration, you would create a new RealmConfiguration object:

// The RealmConfiguration is created using the builder pattern.
// The Realm file will be located in Context.getFilesDir() with name "myrealm.realm"
RealmConfiguration config = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .encryptionKey(getKey())
  .schemaVersion(42)
  .modules(new MySchemaModule())
  .migration(new MyMigration())
  .build();
// Use the config
Realm realm = Realm.getInstance(config);

You can have multiple RealmConfiguration objects, so you can control the version, schema and location of each Realm independently.

RealmConfiguration myConfig = new RealmConfiguration.Builder()
  .name("myrealm.realm")
  .schemaVersion(2)
  .modules(new MyCustomSchema())
  .build();

RealmConfiguration otherConfig = new RealmConfiguration.Builder()
  .name("otherrealm.realm")
  .schemaVersion(5)
  .modules(new MyOtherSchema())
  .build();

Realm myRealm = Realm.getInstance(myConfig);
Realm otherRealm = Realm.getInstance(otherConfig);

Get the absolute path of a Realm by using Realm.getPath.

It is important to note that Realm instances are thread singletons, meaning that the static constructor will return the same instance in response to all calls from a given thread.

The default Realm

The RealmConfiguration can be saved as a default configuration. Setting a default configuration in your custom Application class makes it available in the rest of your code.

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    // The default Realm file is "default.realm" in Context.getFilesDir();
    // we'll change it to "myrealm.realm"
    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration.Builder().name("myrealm.realm").build();
    Realm.setDefaultConfiguration(config);
  }
}

public class MyActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Realm realm = Realm.getDefaultInstance(); // opens "myrealm.realm"
    try {
      // ... Do something ...
    } finally {
      realm.close();
    }
  }
}

Opening a synchronized Realm

Realms on the Realm Object Server are located by URLs, and specified with a SyncConfiguration rather than a RealmConfiguration.

SyncCredentials myCredentials = SyncCredentials.usernamePassword("bob", "greatpassword", true);
SyncUser user = SyncUser.login(myCredentials, serverUrl());
SyncConfiguration config = new SyncConfiguration.Builder(user, realmUrl())
    .schemaVersion(SCHEMA_VERSION)
    .build();
// Use the config
Realm realm = Realm.getInstance(config);

A SyncConfiguration needs, at a minimum, a Realm.SyncUser object and a URL for a Realm Object Server. For more details, read about Users.

Asynchronously opening Realms

Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) will only work from Looper threads.

If opening a Realm requires a time-consuming operation, such as applying migrations, copying files from assets, compaction or downloading the remote contents of a synchronized Realm, you can use Realm.getInstanceAsync. This lets you do any initialization work on a background thread before the calling thread opens the Realm.

RealmConfiguration config = new RealmConfiguration.Builder()
    .schema(42)
    .migration(new MyMigration()) // Potentially lengthy migration
    .build();

RealmAsyncTask task = Realm.getInstanceAsync(config, new Realm.Callback() {
    @Override
    public void onSuccess(Realm realm) {
        // Realm is opened and ready on the caller thread.
    }
});

Initial downloads

In some cases, you might not want to open a Realm until it has all remote data available. For instance, you might want to show the users a list of all available ZIP codes. Use getInstanceAsync with waitForRemoteInitialData. This downloads the Realm in the background before reporting it as ready:

SyncUser user = getUser();
String url = getUrl();
SyncConfiguration config = new SyncConfiguration.Builder(user, url)
    .waitForRemoteInitialData();
    .build();

RealmAsyncTask task = Realm.getInstanceAsync(config, new Realm.Callback() {
    @Override
    public void onSuccess(Realm realm) {
        // Realm is now downloaded and ready. New changes to Realm will continue
        // to be synchronized in the background as normal.
    }
});

Read-only Realms

readOnly is only enforced in the current process. It is still possible for other processes or devices to write to readOnly Realms. Also, any write transaction against a read-only Realm will throw an IllegalStateException. This includes trying to write the schema, so that must be provided initially by some other source.

It’s sometimes useful to ship a prepared Realm file with your app—you may want to bundle some shared data with your application. In many cases you don’t want to accidentally modify that Realm, as the data is purely read-only. You can do this by bundling a Realm file in assets and using a readOnly configuration:

RealmConfiguration config = new RealmConfiguration.Builder()
    .assetFile("my.realm")
    .readOnly()
    // It is optional, but recommended to create a module that describes the classes
    // found in your bundled file. Otherwise if your app contains other classes
    // than those found in the file, it will crash when opening the Realm as the
    // schema cannot be updated in read-only mode.
    .modules(new BundledRealmModule())
    .build();

For synchronized Realms you might want to expose a read-only view of a remote Realm. In that case, you can do the following:

SyncUser user = getUser();
String url = getUrl();
SyncConfiguration config = new SyncConfiguration.Builder(user, url)
    // Similar to `assetFile` for local Realms, but it will fetch all remote
    // data before from the server prior to opening the Realm.
    .waitForRemoteInitialData();
    .readOnly()
    .modules(new BundledRealmModule())
    .build();

RealmAsyncTask task = Realm.getInstanceAsync(config, new Realm.Callback() {
    @Override
    public void onSuccess(Realm realm) {
        // Realm is now downloaded and ready. It is readonly locally but will
        // still see new changes coming from the server.
    }
});

In-memory Realms

With an inMemory configuration, you can create a Realm that runs entirely in memory without being persisted to disk.

RealmConfiguration myConfig = new RealmConfiguration.Builder()
    .name("myrealm.realm")
    .inMemory()
    .build();

In-memory Realms might still use disk space if memory is running low, but all files created by an in-memory Realm will be deleted when the Realm is closed. Creating an in-memory Realm with the same name as a persisted Realm isn’t allowed—names still have to be unique.

When all in-memory Realm instances with a particular name go out of scope with no references, that frees all that Realm’s data. To keep an in-memory Realm “alive” throughout your app’s execution, hold onto a reference to it.

Dynamic Realms

When working with a conventional Realm, the model class is defined using RealmObject subclasses. This has a lot of benefits with regards to type safety. But sometimes, the types aren’t available until runtime, e.g., during migrations, or when working with string-based data like CSV files. Dynamic Realms to the rescue!

A DynamicRealm is a variant of the conventional Realm that makes it possible to work with Realm data without using RealmObject subclasses. Instead, all access is done using Strings instead of Classes.

Opening a Dynamic Realm uses the same configuration as a conventional Realm but the Dynamic Realm ignores any configured schema, migration, and schema version.

RealmConfiguration realmConfig = new RealmConfiguration.Builder().build();
DynamicRealm realm = DynamicRealm.getInstance(realmConfig);

// In a DynamicRealm all objects are DynamicRealmObjects
realm.beginTransaction();
DynamicRealmObject person = realm.createObject("Person");
realm.commitTransaction();

// All fields are accessed using strings
String name = person.getString("name");
int age = person.getInt("age");

// An underlying schema still exists, so accessing a field that does not exist
// will throw an exception
person.getString("I don't exist");

// Queries still work normally
RealmResults<DynamicRealmObject> persons = realm.where("Person")
    .equalTo("name", "John")
    .findAll();

A DynamicRealm gains flexibility at the expense of both type safety and performance; in general, you should be using normal Realms. Only use Dynamic Realms when you need that flexibility.

Closing Realms

Realm implements Closeable to take care of native memory deallocation and file descriptors, so always close your Realm instances when you’re done with them.

Realm instances are reference counted—if you call getInstance twice in a thread, you need to call close twice as well. This allows you to implement Runnable classes without having to worry about which thread will execute them: simply start it with getInstance and end it with close.

For the UI thread, the easiest way is to execute realm.close in the owning component’s onDestroy method. If you need to create a Looper thread other than UI, you can use this pattern:

public class MyThread extends Thread {

    private Realm realm;

    @Override
    public void run() {
        Looper.prepare();
        realm = Realm.getDefaultInstance();
        try {
            //... Setup the handlers using the Realm instance ...
            Looper.loop();
        } finally {
            realm.close();
        }
    }
}

For AsyncTask this is a good pattern:

protected Void doInBackground(Void... params) {
    Realm realm = Realm.getDefaultInstance();
    try {
        // ... Use the Realm instance ...
    } finally {
        realm.close();
    }

    return null;
}

If you are using Thread or Runnable for short-lived tasks:

// Run a non-Looper thread with a Realm instance.
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        Realm realm = Realm.getDefaultInstance();
        try {
            // ... Use the Realm instance ...
        } finally {
            realm.close();
        }
    }
});

thread.start();

If you’re working on an app with minSdkVersion >= 19 and Java >= 7, then you can use try-with-resources:

try (Realm realm = Realm.getDefaultInstance()) {
    // No need to close the Realm instance manually
}

Auto-Refresh

If you obtain a Realm instance from a thread associated with a Looper, the Realm instance comes with an auto-refresh feature. (Android’s UI thread is a Looper.) This means the Realm instance will be periodically updated to the latest version. This lets you keep your UI constantly updated with the latest content with almost no effort!

If you get a Realm instance from a thread that does not have a Looper attached, objects from that instance won’t be updated until you call the waitForChange method. Holding on to an old version of your data is expensive in terms of memory and disk space, and the cost increases with the number of versions between the one being retained and the latest. This is why it is important to close the Realm instance as soon as you are done with it in the thread.

If you want to check whether your Realm instance has auto-refresh activated or not, use the isAutoRefresh method.

Models

Create Realm models by extending the RealmObject base class:

public class User extends RealmObject {

    private String          name;
    private int             age;

    @Ignore
    private int             sessionId;

    // Standard getters & setters generated by your IDE…
    public String getName() { return name; }
    public void   setName(String name) { this.name = name; }
    public int    getAge() { return age; }
    public void   setAge(int age) { this.age = age; }
    public int    getSessionId() { return sessionId; }
    public void   setSessionId(int sessionId) { this.sessionId = sessionId; }
}

A Realm model class supports public, protected and private fields, as well as custom methods.

public class User extends RealmObject {

    public String name;

    public boolean hasLongName() {
      return name.length() > 7;
    }

    @Override
    public boolean equals(Object o) {
      // Custom equals comparison
    }
}

Field types

Realm supports boolean, byte, short, int, long, float, double, String, Date and byte[] field types. The integer types byte, short, int, and long are all mapped to long within Realm. In addition to those standard field types, Realm supports subclasses of RealmObject and RealmList<? extends RealmObject> to model relationships.

The boxed types Boolean, Byte, Short, Integer, Long, Float and Double can also be used in model classes. These types may have the value null.

Required fields

The @Required annotation can be used to tell Realm to disallow null values in a field, making it required rather than optional. Only Boolean, Byte, Short, Integer, Long, Float, Double, String, byte[] and Date can be annotated with @Required. If you add it to other field types, compilation will fail.

Fields with primitive types and the RealmList type are required implicitly. Fields with RealmObject type are always nullable.

Primary keys

To mark a field as a model’s primary key, use the annotation @PrimaryKey. The field type must be either a string (String) or an integer (byte, short, int, long, Byte, Short, Integer, and Long). Using a string field as a primary key automatically indexes the field: the annotation @PrimaryKey on a string implicitly sets the annotation @Index. Realm doesn’t support compound keys, i.e., using multiple fields as a single primary key.

Using primary keys makes it possible to use the copyToRealmOrUpdate method. This looks for an object with a given primary key, and either updates it (if an object with that key already exists) or creates it (if the key does not exist). If you call copyToRealmOrUpdate on a class without a primary key, an exception will be thrown.

When you use primary keys, reads (queries) will be slightly faster, but writes (creating and updating objects) will be a little slower. The changes in performance will depend on the size of your Realm’s data set.

Note that Realm.createObject returns a new object with all fields set to their default values. If the object is a class with a primary key, this could create a conflict—there might be an object with that primary key set already. To avoid this, you can create an unmanaged object, set its field values, then add it to the Realm with copyToRealm:

final MyObject obj = new MyObject();
obj.setId(42);
obj.setName("Fish");
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // This will create a new object in Realm or throw an exception if the
        // object already exists (same primary key)
        // realm.copyToRealm(obj);

        // This will update an existing object with the same primary key
        // or create a new object if an object with no primary key = 42
        realm.copyToRealmOrUpdate(obj);
    }
});

Primary keys that are String types or boxed integers (Byte, Short, Integer, and Long) can have the value null unless the @PrimaryKey annotation is combined with @Required.

Indexing properties

To index a field, use the annotation @Index. Like primary keys, this makes writes slightly slower , but makes reads faster. (It also makes your Realm file slightly larger, to store the index.) It’s best to only add indexes when you’re optimizing the read performance for specific situations.

You can index String, byte, short, int, long, boolean and Date fields.

Ignoring properties

If you don’t want to save a field in your model to its Realm, use the annotation @Ignore. You might do this if, for example, your input contains more fields than your model, and you don’t wish to have many special cases for handling these unused data fields.

Fields marked static and transient are always ignored, and do not need the @Ignore annotation.

Counters

Realm offers MutableRealmInteger as a special integer type. MutableRealmInteger exposes an additional API that can more clearly express intent and generate better conflict resolution steps when using Synchronized Realms.

Traditionally, a counter would be implemented by reading a value, incrementing it and setting it (myObj.counter += 1). This will not work well in an asynchronous situation — for example when two clients are offline — because both parties will read a value, say 10, increment it, and store the value as 11. Eventually, when they regain connectivity and try to merge their changes, they’ll agree that the counter is at 11 rather than the expected 12.

MutableRealmIntegers are backed by traditional integer types, so no migration is required when changing a field from byte, short, int or long to MutableRealmInteger.

MutableRealmInteger is not an immutable type standard like primitive number types in Java. It is a live object like RealmObject, RealmResults and RealmList. This means the value contained inside the MutableRealmInteger can change when a Realm is written to. For this reason MutableRealmInteger fields must be marked final.

public class Party extends RealmObject {
{
    public final MutableRealmInteger guests = MutableRealmInteger.valueOf(0);
}

To change the counter value, simply call counter.increment() or counter.decrement().

Party party = realm.where(Party.class).findFirst();
realm.beginTransaction();
party.guests.get(); // 0
party.guests.increment(1); // 1
party.guests.decrement(1); // 0
party.guests.increment(5); // 1
party.guests.decrement(1); // 4
realm.commitTransaction();

To reset the counter, you can assign it a new value using counter.set().

Calling set() can potentially override increment() and decrement() operations coming from other devices pr. the normal last-write-wins merge rules, so mixin these operations should only be done if lossy counters are acceptable.

Party party = realm.where(Party.class).findFirst();
realm.beginTransaction();
party.guests.set(0);
realm.commitTransaction();

Working with RealmObjects

Auto-updating objects

RealmObjects are live, auto-updating views into the underlying data; you never have to refresh objects. Changes to objects are instantly reflected in query results.

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Dog myDog = realm.createObject(Dog.class);
        myDog.setName("Fido");
        myDog.setAge(1);
    }
});
Dog myDog = realm.where(Dog.class).equalTo("age", 1).findFirst();

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Dog myPuppy = realm.where(Dog.class).equalTo("age", 1).findFirst();
        myPuppy.setAge(2);
    }
});

myDog.getAge(); // => 2

This not only keeps Realm fast and efficient, it allows your code to be simpler and more reactive. If your Activity or Fragment is dependent on a specific RealmObject or RealmResults instance, you don’t need worry about refreshing or re-fetching it before updating the UI.

You can subscribe to Realm notifications to know when Realm data is updated.

Customizing objects

It is possible to use a RealmObject almost like a POJO. Extend your class from RealmObject. You can let the fields be public, and can use simple assignments instead of setters and getters.

public class Dog extends RealmObject {
    public String name;
    public int age;
}

You can use Dog like any other class: you can add logic to your getter and setter methods (for example, for validation), and you can add any custom methods you wish.

To add your Dog object to a Realm, use the createObject or copyToRealm methods:

realm.executeTransaction(new Realm.Transaction() {
    @Overrride
    public void execute(Realm realm) {
        Dog dog = realm.createObject(Dog.class);
        dog.name = "Fido";
        dog.age  = 5;
    }
};

RealmModel interface

Instead of extending RealmObject, your classes can implement the RealmModel interface, adding the @RealmClass annotation:

@RealmClass
public class User implements RealmModel {

}

With this interface, all methods available on RealmObject become available through static methods. Note that a class that extends RealmObject does not need either the @RealmClass annotation or to implement RealmModel.

// With RealmObject
user.isValid();
user.addChangeListener(listener);

// With RealmModel
RealmObject.isValid(user);
RealmObject.addChangeListener(user, listener);

JSON

You can add a JSON object that maps to a RealmObject to Realm. The JSON object can be a String, a JSONObject or an InputStream. Realm will ignore any properties in the JSON not defined by the RealmObject. Add single objects through Realm.createObjectFromJson, and lists of objects through Realm.createAllFromJson.

// A RealmObject that represents a city
public class City extends RealmObject {
    private String city;
    private int id;
    // getters and setters left out ...
}

// Insert from a string
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        realm.createObjectFromJson(City.class, "{ city: \"Copenhagen\", id: 1 }");
    }
});

// Insert multiple items using an InputStream
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        try {
            InputStream is = new FileInputStream(new File("path_to_file"));
            realm.createAllFromJson(City.class, is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
});

If a field in the JSON object is null and the field is required by the Realm model, Realm will throw an exception. If the field is optional, its value will be set to the field default when creating an object, and to null when updating an object. If the Realm model has a field that isn’t present in the JSON object, the value will remain unchanged in the Realm model.

Adapters

Realm offers abstract utility classes to help bind data coming from OrderedRealmCollections (both RealmResults and RealmList implement this interface) to standard UI widgets.

To use the adapters, add the dependencies to the application level build.gradle:

dependencies {
    compile 'io.realm:android-adapters:2.0.0'
}

Intents

Since RealmObjects are not Parcelable and cannot be passed directly, you must pass an identifier for the object you’re working with. For example, if an object has a primary key, pass the primary key value in the Intent extras bundle:

// Assuming we had a person class with a @PrimaryKey on the 'id' field ...
Intent intent = new Intent(getActivity(), ReceivingService.class);
intent.putExtra("person_id", person.getId());
getActivity().startService(intent);

Retrieve the primary key value from the bundle on the receiving end (Activity, Service, IntentService, BroadcastReceiver, etc.), and then open a Realm and query for the RealmObject:

// in onCreate(), onHandleIntent(), etc.
String personId = intent.getStringExtra("person_id");
Realm realm = Realm.getDefaultInstance();
try {
    Person person = realm.where(Person.class).equalTo("id", personId).findFirst();
    // do something with the person ...
} finally {
    realm.close();
}

The overhead for re-opening the Realm on a different thread is very small.

You can find working examples in the Object Passing portion of the threading example. The example shows you how to pass id’s and retrieve the RealmObject in common Android use cases.

Relationships

You can link any two RealmObjects together. Relationships are cheap in Realm: traversing links isn’t expensive in terms of speed or memory. Let’s explore the different types of relationships Realm lets you define between objects.

Many-to-one

To set up a many-to-one or one-to-one relationship, give a model a property whose type is one of your RealmObject subclasses:

public class Email extends RealmObject {
    private String address;
    private boolean active;
}

public class Contact extends RealmObject {
    private String name;
    private Email email;
}

Contact bob = realm.createObject(Contact.class);
bob.name = "Bob Newhart";

Email email1 = realm.createObject(Email.class);
email1.address = "[email protected]";

bob.email = email1;

Each Contact has zero or one Email instances. Nothing would prevent you from using the same Email object with more than one Contact; the distinction between a many-to-one and a one-to-one relationship is up to your application.

Setting the relationship field to null will clear the reference:

bob.email = null;

This deletes the relationship between bob and email1, but email1 is still in the Realm.

Many-to-many

You can create a relationship to any number of objects from a single object via a RealmList<T> field declaration. Let’s rewrite our example to support multiple email addresses:

public class Contact extends RealmObject {
    public String name;
    public RealmList<Email> emails;
}

public class Email extends RealmObject {
    public String address;
    public boolean active;
}

RealmLists are containers of RealmObjects; a RealmList behaves like a regular Java List. You can use the same object in different RealmLists, and you can use this to model both one-to-many and many-to-many relationships.

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Contact contact = realm.createObject(Contact.class);
        contact.name = "John Doe";

        Email email1 = realm.createObject(Email.class);
        email1.address = "[email protected]";
        email1.active = true;
        contact.emails.add(email1);

        Email email2 = realm.createObject(Email.class);
        email2.address = "[email protected]";
        email2.active = false;
        contact.emails.add(email2);
    }
});

It is possible to declare recursive relationships which can be useful when modeling certain types of data.

public class Person extends RealmObject {
    public String name;
    public RealmList<Person> friends;
    // Other fields...
}

Setting the value to null for a RealmList field will clear the list. The list will be empty (length zero), but the objects that were in the list won’t be deleted from the Realm. The getter for a RealmList will never return null: the returned object is always a list. The length might be zero.

Inverse relationships

Relationships are unidirectional. Take the two classes Person and Dog as an example:

public class Dog extends RealmObject {
    private String name;
    private int age;
}

public class Person extends RealmObject {
    @PrimaryKey
    private long id;
    private String name;
    private RealmList<Dog> dogs;
}

You can follow the link from a Person to a Dog, but there’s no way to go from a Dog to its Person objects. You can resolve this by giving the Dog a @LinkingObjects annotation.

public class Person extends RealmObject {
  private String id;
  private String name;
  private RealmList<Dog> dogs;
  // getters and setters
}

public class Dog extends RealmObject {
  private String id;
  private String name;
  private String color;
  @LinkingObjects("dogs")
  private final RealmResults<Person> owners;
  // getters and setters
}

We’ve given Dog an owners field, and specified that it should contain all Person objects that have this Dog object in their dogs field.

The annotated field must be declared final, and must be of type RealmResults<T> where T is the type/class of opposite end of the relationship. Since relationships are either many-to-one or many-to-many, following inverse relationships could result in 0, 1 or more objects.

Like any other RealmResults set, you can query an inverse relationship.

Schemas

The default schema for a Realm is simply all the Realm model classes in a project. However, you can change this behavior—for instance, you might want to restrict a Realm to only contain a subset of classes. To do this, create a custom RealmModule.

// Create the module
@RealmModule(classes = { Person.class, Dog.class })
public class MyModule {
}

// Set the module in the RealmConfiguration to allow only classes defined by the module.
RealmConfiguration config = new RealmConfiguration.Builder()
  .modules(new MyModule())
  .build();

// It is possible to combine multiple modules to one schema.
RealmConfiguration config = new RealmConfiguration.Builder()
  .modules(new MyModule(), new MyOtherModule())
  .build();

For library developers: Libraries that include Realm must expose and use their schema through a RealmModule. Doing so prevents the default RealmModule from being generated for the library project, which would conflict with the default RealmModule used by the app. The library’s RealmModule is also how the library exposes its Realm classes to the app.

// A library must create a module and set library = true. This will prevent the default
// module from being created.
// allClasses = true can be used instead of listing all classes in the library.
@RealmModule(library = true, allClasses = true)
public class MyLibraryModule {
}

// Library projects are therefore required to explicitly set their own module.
RealmConfiguration libraryConfig = new RealmConfiguration.Builder()
  .name("library.realm")
  .modules(new MyLibraryModule())
  .build();

// Apps can add the library RealmModule to their own schema.
RealmConfiguration config = new RealmConfiguration.Builder()
  .name("app.realm")
  .modules(Realm.getDefaultModule(), new MyLibraryModule())
  .build();

You can’t have multiple RealmModule declarations in a single file. If you have two or more RealmModules, you will have to split the declarations into several files with exactly one declaration per file.

See a complete example of how RealmModules work between library and app projects here.

Writes

Unlike read operations, write operations in Realm must be wrapped in transactions. At the end of a write operation, you can either commit the transaction or cancel it. Committing a transaction writes all changes to disk (and if the Realm is synced, queues it for synchronization with Realm Object Server). If you cancel a write transaction, all the changes are discarded. Transactions are “all or nothing”: either all the writes within a transaction succeed, or none of them take effect. This helps guarantee data consistency, as well as providing thread safety.

// Obtain a Realm instance
Realm realm = Realm.getDefaultInstance();

realm.beginTransaction();

//... add or update objects here ...

realm.commitTransaction();

Or to discard the changes by canceling the transaction:

realm.beginTransaction();
User user = realm.createObject(User.class);

//  ...

realm.cancelTransaction();

Write transactions block each other. This can cause ANR errors if you create write transactions on both the UI and background threads at the same time. To avoid this, use async transactions when creating write transactions on the UI thread.

If an exception happens inside a transaction, you’ll lose the changes in that transaction, but the Realm itself won’t be affected (or corrupted). If you catch the exception and the app continues, you’ll need to cancel the transaction. If you use executeTransaction, this happens automatically.

Thanks to Realm’s MVCC architecture, reads are not blocked while a write transaction is open. Unless you need to make simultaneous transactions from many threads at once, you can favor larger transactions that do more work over many fine-grained transactions. When you commit a write transaction to a Realm, all other instances of that Realm will be notified and be updated automatically.

Read & write access in Realm is ACID.

Creating objects

Wrap the createObject method in a write transaction.

realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("[email protected]");
realm.commitTransaction();

If you create an object instance first and use copyToRealm to add it to a Realm, you should wrap the copy action in a transaction, too. Realm supports as many custom constructors as you like as long as one of them is a public no-arguments constructor.

User user = new User("John");
user.setEmail("[email protected]");

// Copy the object to Realm. Any further changes must happen on realmUser
realm.beginTransaction();
User realmUser = realm.copyToRealm(user);
realm.commitTransaction();

Remember, Realm only manages the returned object (realmUser in this example), not the object originally copied (user). To make changes to the object in the database, make changes to the returned copy, not the original.

Transaction blocks

Instead of manually keeping track of beginTransaction, commitTransaction, and cancelTransaction, you can use the executeTransaction method, which will automatically handle begin/commit, and cancel if an error happens.

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        User user = realm.createObject(User.class);
        user.setName("John");
        user.setEmail("[email protected]");
    }
});

Asynchronous transactions

Since transactions are blocked by other transactions, you might want to write on a background thread to avoid blocking the UI thread. By using an asynchronous transaction, Realm will run that transaction on a background thread.

realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm bgRealm) {
                User user = bgRealm.createObject(User.class);
                user.setName("John");
                user.setEmail("[email protected]");
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                // Transaction was a success.
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                // Transaction failed and was automatically canceled.
            }
        });

OnSuccess and OnError callbacks are both optional, but if provided, they will be called when the transaction succeeds or fails, respectively. Callbacks are controlled by the Looper, so they are only allowed on Looper threads.

RealmAsyncTask transaction = realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm bgRealm) {
                User user = bgRealm.createObject(User.class);
                user.setName("John");
                user.setEmail("[email protected]");
            }
        }, null);

The RealmAsyncTask object can cancel any pending transaction if you need to quit the Activity/Fragment before the transaction is completed. Forgetting to cancel a transaction can crash the app if the callback updates the UI!

public void onStop () {
    if (transaction != null && !transaction.isCancelled()) {
        transaction.cancel();
    }
}

Updating strings and byte arrays

Since Realm operates on fields as a whole, it’s not possible to directly update individual elements of strings or byte arrays. Instead, you’ll need to read the whole field, make a modification to the individual element, and write it back again in a transaction block.

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        bytes[] bytes = realmObject.binary;
        bytes[4] = 'a';
        realmObject.binary = bytes;
    }
});

Queries

All fetches (including queries) are lazy in Realm, and the data is never copied.

Realm’s query engine uses a Fluent interface to construct multi-clause queries.

public class User extends RealmObject {

    @PrimaryKey
    private String          name;
    private int             age;

    @Ignore
    private int             sessionId;

    // Standard getters & setters generated by your IDE…
    public String getName() { return name; }
    public void   setName(String name) { this.name = name; }
    public int    getAge() { return age; }
    public void   setAge(int age) { this.age = age; }
    public int    getSessionId() { return sessionId; }
    public void   setSessionId(int sessionId) { this.sessionId = sessionId; }
}

To find all users named John or Peter, you would write:

// Build the query looking at all users:
RealmQuery<User> query = realm.where(User.class);

// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");

// Execute the query:
RealmResults<User> result1 = query.findAll();

// Or alternatively do the same all at once (the "Fluent interface"):
RealmResults<User> result2 = realm.where(User.class)
                                  .equalTo("name", "John")
                                  .or()
                                  .equalTo("name", "Peter")
                                  .findAll();

This gives you a new instance of the class RealmResults, containing the users with the name John or Peter.

The method findAll executes the query; RealmQuery includes a family of findAll methods:

  • findAll finds all objects that meet the query conditions
  • findAllAsync operates asynchronously on a background thread
  • findAllSorted (and fndAllSortedAsync) sorts findAll results by specific field names
  • findFirst (and findFirstAsync) find the first object that meets the query conditions

For full details, dive into the RealmQuery API reference.

Queries return a list of references to the matching objects, so you work directly with the original objects that matches your query. RealmResults inherits from AbstractList and behaves in similar ways. For example, RealmResults are ordered, and you can access the individual objects through an index. If a query has no matches, the returned RealmResults object will be a list of size(0) (not null).

If you wish to modify or delete objects in a RealmResults set, you must do so in a write transaction.

Note that you can also query relationships: read about link queries.

Filtering

The where method starts a RealmQuery by specifying a model. The filter criteria is specified with predicate methods, most of which have self-explanatory names (e.g., equalTo). A predicate always takes a field name as its first argument.

Not all predicates can be used with all field types; consult the RealmQuery API reference for details.

For all data types, you have the following predicates:

  • equalTo
  • notEqualTo
  • in

To match a field against a list of values, use in. For example, to find the names “Jill,” “William,” or “Trillian”, you can use in("name", new String[]{"Jill", "William", "Trillian"}). The in predicate is applicable to strings, binary data, and numeric fields (including dates).

Numeric data types, including Date, allow these additional predicates:

  • between (includes both end points, i.e., it is a bounded interval)
  • greaterThan
  • lessThan
  • greaterThanOrEqualTo
  • lessThanOrEqualTo

String fields allow these additional predicates:

  • contains
  • beginsWith
  • endsWith
  • like

All four string predicates have an optional third argument to control case sensitivity: Case.INSENSITIVE and Case.SENSITIVE. The default is Case.SENSITIVE.

The predicate like performs glob-style wildcard matching. The matching pattern consists of characters and one or more wildcards:

  • * matches 0 or more Unicode characters
  • ? matches a single Unicode character

For example, consider a Realm with four objects with a field called name which has the values William, Bill, Jill, and Trillian. The predicate like("name", "?ill*") will match the first three objects, and like("name", "*ia?") will match the first and the last object.

Binary data, strings, and lists of RealmObjects (RealmList) may be empty, i.e., have a length of zero. You can check for emptiness with:

  • isEmpty
  • isNotEmpty

If a field is not required, the value can have the value null (recall that fields which are RealmObjects can never be required, and the value can be null). You can check for null with:

  • isNull
  • isNotNull

Logical operators

Conditions are implicitly joined with logical and. Logical or joins must be applied explicitly using or.

public class User extends RealmObject {

    @PrimaryKey
    private String          name;
    private int             age;

    @Ignore
    private int             sessionId;

    // Standard getters & setters generated by your IDE…
    public String getName() { return name; }
    public void   setName(String name) { this.name = name; }
    public int    getAge() { return age; }
    public void   setAge(int age) { this.age = age; }
    public int    getSessionId() { return sessionId; }
    public void   setSessionId(int sessionId) { this.sessionId = sessionId; }
}

You can also group conditions using beginGroup and endGroup to specify order of evaluation:

RealmResults<User> r = realm.where(User.class)
                            .greaterThan("age", 10)  // implicit AND
                            .beginGroup()
                                .equalTo("name", "Peter")
                                .or()
                                .contains("name", "Jo")
                            .endGroup()
                            .findAll();

Negate conditions with not. You can use the not operator with beginGroup/endGroup to negate sub-conditions only. If you wanted to all find users who are not named “Peter” or “Jo,” the query could be:

RealmResult<User> r = realm.where(User.class)
                           .not()
                           .beginGroup()
                                .equalTo("name", "Peter")
                                .or()
                                .contains("name", "Jo")
                            .endGroup()
                            .findAll();

With this particular query, though, it’s easier to use in:

RealmResult<User> r = realm.where(User.class)
                           .not()
                           .in("name", new String[]{"Peter", "Jo"})
                           finalAll();

Sorting

You can sort query results with the sort method.

RealmResults<User> result = realm.where(User.class).findAll();
result = result.sort("age"); // Sort ascending
result = result.sort("age", Sort.DESCENDING);

Sorts are ascending by default; to change that, use Sort.DESCENDING as the second argument. It is possible to sort using multiple fields simultaneously.

Unique values

To return only unique values, use distinct predicate. For example, to find out how many different names you have in your Realm:

RealmResults<Person> unique = realm.where(Person.class).distinct("name");

You can only call distinct on integer and string fields; other field types will throw an exception. As with sorting, you can specify multiple fields.

Chaining queries

You can run additional queries on result sets:

RealmResults<Person> teenagers = realm.where(Person.class).between("age", 13, 20).findAll();
Person firstJohn = teenagers.where().equalTo("name", "John").findFirst();

You can also chain queries on child objects as well. Assume the above Person object has a list of Dog objects.

public class Dog extends RealmObject {
    private int age;
    // getters & setters ...
}

public class Person extends RealmObject {
    private int age;
    private RealmList<Dog> dogs;
    // getters & setters ...
}

You can query for all people between the age of 13 and 20 who have at least one dog which is one year old:

RealmResults<Person> teensWithPups = realm.where(Person.class).between("age", 13, 20).equalTo("dogs.age", 1).findAll();

Note that query chains are built on RealmResults, not RealmQuery. When you add more conditions to a RealmQuery object, you are modifying the query itself.

It is possible to query links or relationships. Consider the model below:

public class Person extends RealmObject {
  private String id;
  private String name;
  private RealmList<Dog> dogs;
  // getters and setters
}

public class Dog extends RealmObject {
  private String id;
  private String name;
  private String color;
  // getters and setters
}

Each Person object has multiple dog relationships, as shown in this table diagram:

Table Diagram

Now, we can find specific people with link queries:

// persons => [U1,U2]
RealmResults<Person> persons = realm.where(Person.class)
                                .equalTo("dogs.color", "Brown")
                                .findAll();

The field name in equalTo is a path through the relationships, using a period (.) as the separator. The query above reads “find all Persons who have Dogs whose color is Brown.” Note that the result will contain all Dog objects for Person objects that have at least one matching Dog:

persons.get(0).getDogs(); // => [A,B]
persons.get(1).getDogs(); // => [B,C,D]

Remember, we’re searching for people who have particular kinds of dogs, not the actual dogs themselves.

Let’s dig a little deeper:

// r1 => [U1,U2]
RealmResults<Person> r1 = realm.where(Person.class)
                             .equalTo("dogs.name", "Fluffy")
                             .equalTo("dogs.color", "Brown")
                             .findAll();

// r2 => [U2]
RealmResults<Person> r2 = realm.where(Person.class)
                             .equalTo("dogs.name", "Fluffy")
                             .findAll()
                             .where()
                             .equalTo("dogs.color", "Brown")
                             .findAll()
                             .where()
                             .equalTo("dogs.color", "Yellow")
                             .findAll();

The first query reads, “find all Persons who have dogs named ‘Fluffy’ and have dogs whose color is ‘Brown.’” The second query reads, “find all Persons who have dogs named ‘Fluffy.’ Within that result set, find all Persons who have dogs whose color is ‘Brown.’ Then, within that result set, find all Persons who have dogs whose color is ‘Yellow.’” So the first query finds two sets of Persons and returns the intersection of those sets; the second query operates differently, by taking the result set of each findAll and feeding it into the next where query to successively narrow down the results down. You could rewrite the second query by chaining:

RealmResults<Person> set1 = realm.where(Person.class).equalTo("dogs.name", "Fluffy").findAll();
RealmResults<Person> set2 = set1.where(Person.class).equalTo("dogs.color", "Brown").findAll();
RealmResults<Person> set3 = set2.where(Person.class).equalTo("dogs.color", "Brown").findAll();

Using inverse relationships, you can expand your query possibilities. Let’s consider the same two model classes, Person and Dog. Instead of starting the query with Person, you can query first for the dog, and follow the inverse relationship to the persons.

RealmResults<Dog> brownFluffies = realm.where(Dog.class).equalTo("color", "Brown").equalTo("name", "Fluffy").findAll();
for (Dog brownFluffy : brownFluffies) {
    RealmResults<Person> owners = brownFluffy.getOwners();
    // ...
}

You can also use link queries with inverse relationships:

RealmResults<Dog> dogs = realm.where(Dog.class).equalTo("persons.name", "Jane").findAll();

Auto-updating results

RealmResults are live, auto-updating views into the underlying data. If another thread, process or even device modifies an object in a RealmResults set, the change is instantly reflected. Your code doesn’t need to re-run the query or manually refresh the data.

final RealmResults<Dog> puppies = realm.where(Dog.class).lessThan("age", 2).findAll();
puppies.size(); // => 0

realm.executeTransaction(new Realm.Transaction() {
    @Override
    void public execute(Realm realm) {
        Dog dog = realm.createObject(Dog.class);
        dog.setName("Fido");
        dog.setAge(1);
    }
});

puppies.addChangeListener(new RealmChangeListener() {
    @Override
    public void onChange(RealmResults<Dog> results) {
      // results and puppies point are both up to date
      results.size(); // => 1
      puppies.size(); // => 1
    }
});

This applies to all RealmResults: all objects, filtered and chained.

This property of RealmResults not only keeps Realm fast and efficient, but it allows your code to be simpler and more reactive. For example, if your Activity or Fragment relies on the results of a query, you can just store the Realm object or RealmResults in a field. Its data will always be up-to-date when accessed.

Even though you don’t have to refresh your RealmResults, your application may need to update its UI or run other tasks when data changes. You can subscribe to notifications when Realm data gets updated. Since results are auto-updating, it’s important to not rely on indices and counts staying constant.

Aggregation

RealmResults offers aggregation convenience methods for operations like sums and averages across result sets.

RealmResults<User> results = realm.where(User.class).findAll();
long   sum     = results.sum("age").longValue();
long   min     = results.min("age").longValue();
long   max     = results.max("age").longValue();
double average = results.average("age");

long   matches = results.size();

Iterations & snapshots

All Realm collections are live. This means that they always reflect the latest state. In most cases this is desirable, but what if you’re iterating over a collection with the purpose of modifying the elements? For example:

RealmResults<Person> guests = realm.where(Person.class).equalTo("invited", false).findAll();
realm.beginTransaction();
for (int i = 0; guests.size(); i++) {
    guests.get(i).setInvited(true);
}
realm.commitTransaction();

Typically you would expect this simple loop to invite all guests. Because the RealmResults is updated immediately, though, only half the guests end up being invited! An invited guest is removed immediately from the collection, which will shift all elements. When the i parameter gets incremented, it will miss an element.

To prevent this, you can take a snapshot of a collection’s data. A snapshot guarantees the order of elements will not change, even if an element is deleted or modified.

Iterators created from Realm collections will use a snapshot automatically. RealmResults and RealmList have a createSnapshot method to create one manually.

RealmResults<Person> guests = realm.where(Person.class).equalTo("invited", false).findAll();

// Use an iterator to invite all guests
realm.beginTransaction();
for (Person guest : guests) {
    guest.setInvited(true);
}
realm.commitTransaction();

// Use a snapshot to invite all guests
realm.beginTransaction();
OrderedRealmCollectionSnapshot<Person> guestsSnapshot = guests.createSnapshot();
for (int i = 0; guestsSnapshot.size(); i++) {
    guestsSnapshot.get(i).setInvited(true);
}
realm.commitTransaction();

Deletion

You can delete the results of a query from the Realm:

// obtain the results of a query
final RealmResults<Dog> results = realm.where(Dog.class).findAll();

// All changes to data must happen in a transaction
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // remove single match
        results.deleteFirstFromRealm();
        results.deleteLastFromRealm();

        // remove a single object
        Dog dog = results.get(5);
        dog.deleteFromRealm();

        // Delete all matches
        results.deleteAllFromRealm();
    }
});

Asynchronous queries

Most queries in Realm are fast enough to run synchronously, even on the UI thread. However for either complex queries or queries on large data sets, it can be an advantage to run the query on a background thread.

RealmResults<User> result = realm.where(User.class)
                              .equalTo("name", "John")
                              .or()
                              .equalTo("name", "Peter")
                              .findAllAsync();

Note that the query is not blocking—it immediately returns a RealmResults<User>. This is a promise similar to the concept of a Future in standard Java. The query will continue to run in a background thread, updating the returned instance of RealmResults once it’s finished.

If you want to be notified when the query completes and the RealmResults object is updated, you can register a RealmChangeListener. This listener will be called every time the RealmResults are updated to reflect the latest changes in the Realm (usually after a commit).

private OrderedRealmCollectionChangeListener<RealmResults<User> callback = new OrderedRealmCollectionChangeListener<>() {
    @Override
    public void onChange(RealmResults<User> results, OrderedCollectionChangeSet changeSet) {
        if (changeSet == null) {
            // The first time async returns with an null changeSet.
        } else {
            // Called on every update.
        }
    }
};

private RealmResults<User> result;

public void onStart() {
    result = realm.where(User.class).findAllAsync();
    result.addChangeListener(callback);
}

Remember to unregister any listeners when exiting an Activity or Fragment to avoid memory leaks.

public void onStop () {
    result.removeChangeListener(callback); // remove a particular listener
    // or
    result.removeAllChangeListeners(); // remove all registered listeners
}

Use isLoaded to check if a query has completed:

RealmResults<User> result = realm.where(User.class).findAllAsync();
if (result.isLoaded()) {
  // Results are now available
}

Calling isLoaded on a RealmResults object obtained synchronously will always return true.

You can also wait until the query completes. This will block the thread, making the query synchronous again.

RealmResults<User> result = realm.where(User.class).findAllAsync();
result.load() // be careful, this will block the current thread until it returns

Note: You can only use asynchronous queries on a Looper thread. The asynchronous query needs to use the Realm’s Handler in order to deliver results consistently. Trying to call an asynchronous query using a Realm opened inside a thread without a Looper will throw an IllegalStateException.

Migrations

When working with any database, it is likely your model classes (i.e. your database schema) will change over time. Since model classes in Realm are defined as standard objects, changing the schema is as easy as changing the interface of the corresponding RealmObject subclass.

Local migrations

For Realms that are not synced to the Realm Object Server, performing a migration requires two changes to your RealmConfiguration: setting a new schema version, and writing code to perform the migration.

RealmConfiguration config = new RealmConfiguration.Builder()
    .schemaVersion(2) // Must be bumped when the schema changes
    .migration(new MyMigration()) // Migration to run instead of throwing an exception
    .build()

Using this, the migration code will be run automatically if needed. We provide built-in methods so you can upgrade your schema on disk, and the data you stored for previous versions of the schema.

// Example migration adding a new class
public class MyMigration implements RealmMigration {
  @Override
  public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

     // DynamicRealm exposes an editable schema
     RealmSchema schema = realm.getSchema();

     // Migrate to version 1: Add a new class.
     // Example:
     // public Person extends RealmObject {
     //     private String name;
     //     private int age;
     //     // getters and setters left out for brevity
     // }
     if (oldVersion == 0) {
        schema.create("Person")
            .addField("name", String.class)
            .addField("age", int.class);
        oldVersion++;
     }

     // Migrate to version 2: Add a primary key + object references
     // Example:
     // public Person extends RealmObject {
     //     private String name;
     //     @PrimaryKey
     //     private int age;
     //     private Dog favoriteDog;
     //     private RealmList<Dog> dogs;
     //     // getters and setters left out for brevity
     // }
     if (oldVersion == 1) {
        schema.get("Person")
            .addField("id", long.class, FieldAttribute.PRIMARY_KEY)
            .addRealmObjectField("favoriteDog", schema.get("Dog"))
            .addRealmListField("dogs", schema.get("Dog"));
        oldVersion++;
     }
  }
}

See our migration sample app for more details.

If there is no file on disk when Realm launches, no migration is needed, and Realm will just create a new .realm file & schema based on the latest models defined in your code. This means that if you are in the middle of development and changing your schema frequently—and it’s all right to lose all your data—you can delete your .realm file on disk instead of writing a migration. This can be helpful when tinkering with models early in the development cycle of your app.

RealmConfiguration config = new RealmConfiguration.Builder()
    .deleteRealmIfMigrationNeeded()
    .build()

Syncing migrations

When your Realm is synced with Realm Object Server, the migration process is a little different—and in many cases, simpler. Here’s what you need to know:

  • You don’t need to set the schema version (although you can).
  • Additive changes, such as adding a class or adding a field to a class, are applied automatically.
  • Removing a field from a schema doesn’t delete the field from the database, but instead instructs Realm to ignore that field. New objects will continue to be created with those properties, but they will be set to null. Non-nullable fields will be set to appropriate zero/empty values: 0 for numeric fields, an empty string for string properties, and so on.
  • You must not include a migration block.

Suppose your application has the Dog class:

public class Dog extends RealmObject {
    private String name = "";
}

Now you need to add the Person class and give it an owner relationship to Dog. You don’t need to do anything other than adding the class and associated properties before syncing:

public class Dog extends RealmObject {
  private String name = "";
  private Person owner;
  // getter / setter
}

public class Person extends RealmObject {
  private String name = "";
  private Date birthdate;
  // getter / setter
}

String syncServerURL = "realm://localhost:9080/Dogs"
SyncConfiguration config = new SyncConfiguration.Builder(user, syncServerURL).build();

Realm realm = Realm.getInstance(config);

Since synced Realms don’t support migration blocks, destructive changes for a migration—changing a primary key, changing field types of existing fields (while keeping the same name), or changing a property from optional to required or vice-versa—need to be handled in a different way. Create a new synchronized Realm with the new schema, and copy data from the old Realm to the new Realm:

public class Dog extends RealmObject {
  private String name = "";
  private Person owner;
  // getter / setter
}

public class Person extends RealmObject {
  private String name = "";
  // getter / setter
}

public class DogV2 extends RealmObject {
  private String name = "";
  // getter / setter
}

@RealmModule(classes = { Person.class, Dog.class }) class InitialModule {}

String syncServerURL = "realm://localhost:9080/Dogs"
SyncConfiguration config = new SyncConfiguration.Builder(user, syncServerURL)
              .modules(new InitialModule())
              .build();
// Limit to initial object type
Realm initialRealm = Realm.getInstance(config);



@RealmModule(classes = { Person.class, DogV2.class }) class NewModule {}

String syncServerURL = "realm://localhost:9080/Dogs"
SyncConfiguration config = new SyncConfiguration.Builder(user, syncServerURL)
              .modules(new NewModule())
              .build();
// Limit to new object type
Realm initialRealm = Realm.getInstance(config);

Your application can do this by listening for notifications on the old Realm, making the changes and copying them to the new Realm. (This is a good use case for Dynamic Realms.) If you’re using Professional or Enterprise Edition, you can also use a Realm Function (or event handler) running on the Object Server.

Notifications

It is possible to register a listener to receive notifications for changes on a Realm or its entities. Realm notifications are sent when the Realm as a whole is changed; collection notifications are sent when individual objects are changed, added, or removed.

Stop notification delivery by calling the removeChangeListener or removeAllChangeListeners method. Notifications will also stop if the object on which the listener is registered gets garbage collected, or if its Realm instance is closed. You should keep a strong reference of the object you’re listening to as long as you need the notifications.

Notifications are always delivered on the thread that they were originally registered on. That thread must have a running Looper. If the relevant write transaction happened on a different thread, the listener will be called asynchronously after the transaction is committed.

If the write transaction happened on the same thread, the listener will be called synchronously when the transaction is committed. However, in some cases the listener may be called when the transaction starts—if the Realm is advanced to the latest version, or Realm entities being observed were modified or deleted in a way that triggers notifications. In those cases, the listener runs within the context of the current write transaction, so an attempt to begin a new write transaction within the notification handler will throw an exception. You can use the Realm.isInTransaction method to determine if your code is executing within a write transaction.

Since asynchronous notifications are delivered through looper events, the delivery of notifications might be delayed by other events in the looper queue. When notifications can’t be delivered immediately, changes from multiple write transactions may be coalesced into a single notification.

Realm notifications

Your UI or other looper threads can get notified of changes in a Realm by adding a listener, which is executed whenever the Realm is changed:

public class MyActivity extends Activity {
    private Realm realm;
    private RealmChangeListener realmListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      realm = Realm.getDefaultInstance();
      realmListener = new RealmChangeListener() {
        @Override
        public void onChange(Realm realm) {
            // ... do something with the updates (UI, etc.) ...
        }};
      realm.addChangeListener(realmListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Remove the listener.
        realm.removeChangeListener(realmListener);
        // Close the Realm instance.
        realm.close();
    }
}

A listener on a Realm receives the entire changed Realm.

Collection notifications

Collection notifications receive not the whole Realm, but instead fine-grained descriptions of changes. These consist of the indices of objects that have been added, removed, or modified since the last notification. Collection notifications are delivered asynchronously, first with the initial results and then again after each write transaction which changes any of the objects in the collection (or adds new ones).

These changes can be accessed via the OrderedCollectionChangeSet parameter that is passed to the change listener. This object holds information about the indices affected by deletions, insertions and changes.

The first two, deletions and insertions, record the indices of objects that have been added to or removed from the collection. This takes into account when you add objects to the Realm or delete them from the Realm. For RealmResults this also applies when you filter for specific values and the object was changed so that it is now matching the query or not matching anymore.

You’re notified about changes whenever a field of an object has changed, which was previously part of the collection and is still part of it. This happens as well when to-one and to-many relationships change.

public class Dog extends RealmObject {
  public String name;
  public int age;
}

public class Person exteds RealmObject {
  public String name;
  public RealmList<Dog> dogs;
}

Let’s assume you’re observing a list of dog owners as given by the model code above. You will be notified about modifications for a matched Person object for example when:

  • You modify the Person’s name.
  • You add or remove a Dog from the list of dogs belonging to a Person.
  • You modify the age of a Dog belonging to that Person.

This makes it possible to discretely control animations and visual updates made to the content inside your UI, instead of arbitrarily reloading everything each time a notification occurs.

private final OrderedRealmCollectionChangeListener<RealmResults<Person>> changeListener = new OrderedRealmCollectionChangeListener<>() {
    @Override
    public void onChange(RealmResults<Person> collection, OrderedCollectionChangeSet changeSet) {
        // `null`  means the async query returns the first time.
        if (changeSet == null) {
            notifyDataSetChanged();
            return;
        }
        // For deletions, the adapter has to be notified in reverse order.
        OrderedCollectionChangeSet.Range[] deletions = changeSet.getDeletionRanges();
        for (int i = deletions.length - 1; i >= 0; i--) {
            OrderedCollectionChangeSet.Range range = deletions[i];
            notifyItemRangeRemoved(range.startIndex, range.length);
        }

        OrderedCollectionChangeSet.Range[] insertions = changeSet.getInsertionRanges();
        for (OrderedCollectionChangeSet.Range range : insertions) {
            notifyItemRangeInserted(range.startIndex, range.length);
        }

        OrderedCollectionChangeSet.Range[] modifications = changeSet.getChangeRanges();
        for (OrderedCollectionChangeSet.Range range : modifications) {
            notifyItemRangeChanged(range.startIndex, range.length);
        }
    }
};

The RealmRecyclerViewAdapter provides this out of the box.

Object notifications

Realm supports object-level notifications. You may register a notification on a particular RealmObject in order to be notified if the object is deleted, or whenever any of the managed fields on the object have their values modified.

Only managed RealmObjects can have listeners registered on them.

These changes can be accessed via the ObjectChangeSet parameter that is passed to the change listener. The ObjectChangeSet holds information about which fields were changed and if the RealmObject was deleted.

The ObjectChangeSet.isDeleted will return true if the object was deleted. After that the listener won’t be called again.

The ObjectChangeSet.getChangedFields will return the names of changed fields if any of the object’s managed fields were changed. You can also use ObjectChangeSet.isFieldChanged to test if a given field was just changed.

private final RealmObjectChangeListener<Dog> listener = new RealmObjectChangeListener<Dog>() {
    @Override
    public void onChange(Dog dog, ObjectChangeSet changeSet) {
        if (changeSet.isDeleted()) {
            Log.i(TAG, "The dog was deleted");
            return;
        }

        for (String fieldName : changeSet.getChangedFields()) {
            Log.i(TAG, "Field " + fieldName + " was changed.");
        }
    }
};

Encryption

Please take note of the Export Compliance section of our LICENSE, as it places restrictions against the usage of Realm if you are located in countries with an export restriction or embargo from the United States.

The Realm file can be encrypted on disk by passing a 512-bit encryption key (64 bytes) to the configuration using RealmConfiguration.Builder.encryptionKey:

byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
RealmConfiguration config = new RealmConfiguration.Builder()
  .encryptionKey(key)
  .build();

Realm realm = Realm.getInstance(config);

When an encryption key is given, Realm transparently encrypts and decrypts data with standard AES-256 encryption. You must supply the same encryption key every time you open that Realm. See examples/encryptionExample for an example of how to securely store keys between runs in the Android KeyStore so that other applications cannot read them.

Users

The central object in the Realm Object Server is the Realm User (SyncUser) associated with a synchronized Realm. A SyncUser authenticates with a shared Realm via a username/password scheme, or through a number of third-party authentication methods.

Creating and logging in a user requires two things:

  • A URL of a Realm Object Server to connect to.
  • Credentials for an authentication mechanism that describes the user as appropriate for that mechanism (i.e., username/password, access key, etc).

Server URL

Just like web pages, Realms are located by URLs. Instead of http:// and https://, use realm:// and realms:// to open Realms (as with HTTP, the -s suffix uses TLS/SSL).

The full form of a Realm URL is:

realm://<servername>/path-to-realm

The path will specify the Realm user ID for a private or shared Realm as its first path segment. Instead of a user ID, yon can specify a tilde character (~), which will be transparently expanded to represent the user ID. This scheme allows you to write your app to cater to its individual users. The location on disk for shared Realms is managed by the framework, but can be overridden if desired.

SyncUser user = getUserFromLogin();
String serverURL = "realm://my.realm-server.com:9080/~/default";
SyncConfiguration configuration = new SyncConfiguration.Builder(user, serverURL).build();

Notice: URLs cannot end with a .realm file extension. They should contain the main part of the name (e.g., default above). Realm will create all the related files and folders to store the data.

For more details about the server URL, please refer to our authentication documentation.

Authentication

Authentication establishes the identity of a user. For a list of authentication providers supported by the Realm Mobile Platform, read our authentication documentation.

You can provide a user’s credentials in one of several ways:

  • A valid username/password combination
  • A token from a supported third-party authentication service
  • A token from a custom authentication provider (see Custom Authentication)

The username and password authentication is entirely managed by the Realm Object Server, giving you full control over your application’s user management. For other authentication methods, your application is responsible for logging into the external service and obtaining the authentication token.

Here are some examples of setting credentials with various providers.

Username/password

SyncCredentials myCredentials = SyncCredentials.usernamePassword(username, password, true);

The third parameter of usernamePassword is a boolean indicating whether the user should be created. Set it to true when registering new users; set it to false when logging in users.

Google

String token = "..."; // a string representation of a token obtained from the Google Login API
SyncCredentials myCredentials = SyncCredentials.google(token);

Facebook

String token = "..."; // a string representation of a token obtained from the Facebook Login API
SyncCredentials myCredentials = SyncCredentials.facebook(token);

Custom authentication

String token = "..."; // a string representation of a token obtained from your authentication server
Map<String, Object> customData = new HashMap<>();
SyncCredentials myCredentials = SyncCredentials.custom(
  token,
  'myauth',
  customData,
);

Note: it is possible to pass additional login information to this constructor as a third parameter. Please see the SyncCredentials API for more information.

SSL/TLS

Before you can use secured realms with realms://, Realm needs the trusted root certificate of the server in PEM format.

Example:

SyncConfiguration syncConfiguration = new SyncConfiguration.Builder(user, "realms://host/~/myapp")
                .serverCertificate("root_ca.pem")
                .build();
realm = Realm.getInstance(syncConfiguration);

Put the root_ca.pem certificate in your project’s assets directory:

.
├── main
│   ├── AndroidManifest.xml
│   ├── assets
│   │   └── root_ca.pem
│   ├── java

It is your responsibility to download and verify the PEM certificate for the root CA you trust. (You can use the list from Mozilla.)

To disable certificate verification (e.g., for debugging, or when using a self-signed certificate), you call disableSSLVerification:

SyncConfiguration syncConfiguration = new SyncConfiguration.Builder(user, "realms://host/~/myapp")
                .disableSSLVerification()
                .build();
realm = Realm.getInstance(syncConfiguration);

Logging in

Once you have the credentials, you can log the user into the Realm Object Server:

String authURL = "http://my.realm-auth-server.com:9080/auth";
SyncUser user = SyncUser.login(myCredentials, authURL);

You can have more than one user logged into the Object Server at once. For example, an email client might support connecting to multiple email accounts; multiple users—one for each account—can be logged in simultaneously.

Working with users

The currentUser is the last logged-in user whose credentials are still unexpired:

SyncUser user = SyncUser.currentUser();

To get all logged-in users, use all:

Map<String, SyncUser> users = SyncUser.all();

If no users are logged in, the map returned will be empty.

You can also convert a user object to JSON format:

String userJson = user.toJson();

You can store this to recreate the user object and refresh the user’s access tokens without requiring them to log in again at a third-party provider:

SyncUser user = SyncUser.fromJson(userJson);

Realm saves the current user using a UserStore. The default UserStore is backed by a private Shared Preference file; this can be overridden using SyncManager.setUserStore. Remember that user objects are sensitive data!

Logging out

Logging out of a synced Realm is simple:

user.logout();

When a user logs out, synchronization stops; all Realms belonging to the user must be closed before the user can log out. A logged out user can no longer open a Realm using a SyncConfiguration.

Admin users

Admin users have management-level access to all Realms on the Realm Object Server. Use the SyncUser.isAdmin method to test whether a user is an admin:

SyncUser user = SyncUser.login(credentials, serverURL);
if (user != null) {
    // user.isAdmin() => the user is an admin user
}

This reflects the user’s access at the time of its last successful login.

Access control

The Realm Mobile Platform provides flexible access control mechanisms to restrict which users are allowed to sync against which Realm files. This can be used, for example, to create collaborative apps where multiple users write to the same Realm. It can also be used to share data in a publisher/subscriber scenario where a single writing user shares data with many users with read permissions.

There are four axes that control the access level (permissions) of a given Realm:

  • AccessLevel.NONE indicates that the user is not allowed to access this Realm in any way.
  • AccessLevel.READ indicates that the user is allowed to read from the Realm.
  • AccessLevel.WRITE indicates that the user is allowed to write to the Realm.
  • AccessLevel.ADMIN indicates that the user is allowed to change the permissions for the Realm.

Unless permissions are explicitly modified, only the owner (creator) of a Realm can access it. The only exception is admin users: They are always granted all permissions to all Realms on the server.

Please refer to the general Realm Object Server documentation on Access Control to learn more about the concept.

Permission Manager

Permissions are controlled by users through their PermissionManager. The PermissionManager offer helper API’s for most common operations that are described in the following sections.

The PermissionManager is a wrapper for the underlying permission system Realms, for that reason, opening the PermissionManager is restricted to the UI thread and all data coming from the PermissionManager is also thread confined. When the Permission Manager no longer is needed it must be closed to avoid leaking ressources.

It also means that that queries and change listeners work as normal and be be used to filter or listen for any further changes.

SyncUser user = getUser();

// Must be called on the UI thread
PermissionManager pm = user.getPermissionManager();

// Do work...

// Close when done
pm.close();

Retrieving Permissions

To get a collection of all the Permissions a user has been granted, use the getPermissions(callback) method:

PermissionManager pm = user.getPermissionManager();

// Retrieve 
pm.getPermissions(new PermissionManager.PermissionsCallback() {
    @Override
    public void onSuccess(RealmResults<Permission> permissions) {

        // Permissions can be queried like normal
        Permission p = permissions.where().equalTo("path", realmPath).findFirst();

        // Changelisteners can be registered 
        // The PermissionManager keeps a reference to these as long as the Permission Manager
        // is open, so they do not risk getting GC'ed
        permissions.addChangeListener(new RealmChangeListener() {
            @Override
            public void onChange(RealmResults<Permission> permissions) {
                // Permissions changed
            }
        });
    }

    @Override
    public void onError(ObjectServerError error) {
        // handle error  
    }
});

Granting Permissions

Permission changes can be applied (i.e. granted or revoked) via the [applyPermissions(permissionRequest, callback) method in order to directly increase or decrease other users’ access to a Realm.

PermissionManager pm = user.getPermissionManager();

// Create request
UserCondition condition = UserCondition.userId(user.getIdentity());
AccessLevel accessLevel = AccessLevel.WRITE;
PermissionRequest request = new PermissionRequest(condition, url, accessLevel);

pm.applyPermissions(request, new PermissionManager.ApplyPermissionsCallback() {
    @Override
    public void onSucesss() {
        // Permissions where succesfully changed
    }

    @Override
    public void onError(ObjectServerError error) {
        // Something went wrong
    }
});

UserCondition specifies which users are effected and has 3 factory methods: - userId() - use this to apply permissions based on a user’s Identity(the internal Id that Realm generates). - userName() - use this to change permissions by specifying a user’s username in the Username/Password provider. This is normally their email address. - nonExistingPermissions() - use this to apply the permissions to all users not already having access to the Realm. This can e.g. be useful to give everyone read access to a Realm without having to enumerate them.

The last argument controls the AccessLevel that the user will be granted. Higher access implies all lower tiers, e.g. WRITE implies READ, ADMIN implies READ and WRITE. If AccessLevel.NONE is passed, this will revoke the user’s permissions for this Realm.

Permission Offers

In some situations you want to grant permissions to users, but either you don’t know who they are or perhaps you want to extend the offer through a different channel like email. Examples are scanning a QR code or sending access over an email.

In those cases, you can create a permission offer token that represents the intent of getting access, but access is not given until the receiver accepts the token.

A user can create this opaque token returned by makeOffer(offer, callback):

PermissionManager pm = user.getPermissionManager();

// Create Offer
String realmUrl = "realm://my-server.com/~/myRealm";
Date expiresAt = new Date(2017, 08, 25);
AccessLevel accessLevel = AccessLevel.READ;
PermissionOffer offer = new PermissionOffer(realmUrl, accessLevel, expiresAt);

// Accept token
pm.makeOffer(offer, new PermissionManager.MakeOfferCallback() {
    @Override
    public void onSucces(String token) {
        // Send token to other users
    }

    @Override
    public void onError(ObjectServerError error) {
        // An error happened
    }
});

The optional expiresAt argument controls when the offer expires - i.e. using the token after that date will no longer grant permissions to that Realm. You can also revoke the token manually using revokeOffer(token, callback).

Users who have already consumed the token to obtain permissions will not lose their access if the token is revoked or expires.

Once a user has received a token they can consume it to obtain the permissions offered:

PermissionManager pm = user.getPermissionManager();

String token = getToken();
var realmUrl = pm.acceptOffer(token,  new PermissionManager.AcceptOfferCallback() {
    @Override
    public void onSucces(String realmUrl, Permission permission) {
        // User can now access the Realm
        SyncConfiguration config = new SyncConfiguration.Builder(realmUrl, user).build();
        Realm realm = Realm.getInstance(config);
    }

    @Override
    public void onError(ObjectServerError error) {
        // An error happened
    }
});

In some cases you might want to revoke existing offers after an app has been restarted. In that case, it is possible to get a list of all existing offers using getCreatedOffers(callback).

PermissionManager pm = user.getPermissionManager();
user.getCreatedOffers(new PermissionManager.OffersCallback() {
    @Override
    public void onSuccess(RealmResults<PermissionOffer> offers) {
        for (PermissionOffer offer : offers) {
            // Handle individual offer
        }
    }

    @Override
    public void onError(ObjectServerError error) {
        // handle error
    }
});

Working with synced Realms

Sync sessions

A synced Realm’s connection to the Realm Object Server is represented by a SyncSession object. A session object for a specific Realm can be retrieved by using the SyncManager.getSession(SyncConfiguration) API.

Progress notifications

Session objects allow your app to monitor the status of a session’s uploads to and downloads from the Realm Object Server by registering progress notifications on a session object.

Progress notifications are invoked periodically by the synchronization subsystem. The notification callback will happen on a worker thread, so manipulating UI elements must be done using Activity.runOnUiThread or similar. As many notifications as needed can be registered on a session object simultaneously. Notifications can either be configured to report upload progress or download progress.

Each time a notification is called, it will receive the number of bytes already transferred, as well as the total number of transferrable bytes (the number of bytes already transferred plus the number of bytes pending transfer).

Notifications can be un-registered by using SyncSession.removeProgressListener.

There are two types of notification modes: ProgressMode.CURRENT_CHANGES and ProgressMode.INDEFINITELY. Notifications configured with ProgressMode.INDEFINITELY will remain active unless explicitly stopped by the user and will always report the most up-to-date number of transferrable bytes. This type of block could be used to control a network indicator UI that, for example, changes color or appears only when uploads or downloads are actively taking place. A notification in this mode can report Progress.isTransferComplete multiple times.

ProgressListener listener = new ProgressListener() {
    @Override
    public void onChange(Progress progress) {
        activity.runOnUiThread(new Runnable) {
            @Override
            public void run() {
                if (progress.isTransferComplete()) {
                    hideActivityIndicator();
                } else {
                    showActivityIndicator();
                }
            }
        }
    }
};

SyncSession session = SyncManager.getSession(getSyncConfiguration());
session.addDownloadProgressListener(ProgressMode.INDEFINITELY, listener);

// When stopping activity
session.removeProgressListener(listener);

Notifications configured with ProgressMode.CURRENT_CHANGES only report progress for currently outstanding work. These notifications capture the number of transferrable bytes at the moment they are registered and always report progress relative to that value. Once the number of transferred bytes reaches or exceeds that initial value, the notification will send one final event where Progress.isTransferComplete is true and then never again. The listener should be unregistered at this point. This type of notification could, for example, be used to control a progress bar that tracks the progress of an initial download of a synced Realm when a user signs in, letting them know when their local copy is up-to-date.

final SyncSession session = SyncManager.getSession(getSyncConfiguration());
ProgressListener listener = new ProgressListener() {
    @Override
    public void onChange(Progress progress) {
        activity.runOnUiThread(new Runnable) {
            @Override
            public void run() {
                if (progress.isTransferComplete()) {
                    hideProgressBar();
                    session.removeProgressListener(this);
                } else {
                    updateProgressBar(progress.getFractionTransferred());
                }
            }
        }
    }
};
setupProgressBar();
session.addDownloadProgressListener(ProgressMode.CHANGES_ONLY, listener);

Logging

Debugging synced Realms can be cumbersome, and logging is important to gain insights to issues. By enabling more verbose logs, you can better see what is happening through Android logcat.

RealmLog.setLevel(Log.VERBOSE);

Error reporting

It is possible to set up error handling by registering an error handler:

SyncConfiguration configuration = new SyncConfigurtion.Builder(user, serverURL)
  .errorHandler(new Session.ErrorHandler() {
    void onError(Session session, ObjectServerError error) {
        // do some error handling
    }
  })
  .build();

It is also possible to register a default global error handler that will apply to all SyncConfigurations:

SyncManager.setDefaultSessionErrorHandler(myErrorHandler);

Conflict resolution

For information about how the Realm Object Server handles syncing conflicts, read conflict resolution in the Object Server documentation.

Threading

Realm makes it effortless to work with data on multiple threads without having to worry about consistency or performance, because objects and queries are auto-updating at all times. You can operate on live objects in different threads, reading and writing to them, without worrying about what other threads are doing to those same objects. If you need to change data, you can use a transaction. The other objects in the other threads will be updated in near real time (the updates will be scheduled as an event on the Looper, so Looper threads will be updated as soon as the event is processed).

The only limitation is that you cannot randomly pass Realm objects between threads. If you need the same data on another thread, you need to query for that data on the that other thread. Furthermore, you can observe the changes using Realms reactive architecture. Remember, all objects are kept up to date between threads—Realm will notify you when the data changes.

Threading example

Assume we have an app that displays a list of customers. In a background thread (an Android IntentService) we poll a remote endpoint for new customers and then save them to Realm. When the background thread adds new customers, the data in the UI thread will be automatically updated. The UI thread gets notified via a RealmChangeListener and at that point we tell the UI widget to update itself. No need to re-query because Realm keeps everything up to date.

// in a Fragment or Activity, etc
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // ... boilerplate omitted for brevity
    realm = Realm.getDefaultInstance();
    // get all the customers
    RealmResults<Customer> customers = realm.where(Customer.class).findAllAsync();
    // ... build a list adapter and set it to the ListView/RecyclerView/etc

    // set up a Realm change listener
    changeListener = new RealmChangeListener() {
        @Override
        public void onChange(RealmResults<Customer> results) {
            // This is called anytime the Realm database changes on any thread.
            // Please note, change listeners only work on Looper threads.
            // For non-looper threads, you manually have to use Realm.waitForChange() instead.
            updateUi();
        }
    };
    // Tell Realm to notify our listener when the customers results
    // have changed (items added, removed, updated, anything of the sort).
    customers.addChangeListener(changeListener);
}

// In a background service, in another thread
public class PollingService extends IntentService {
    @Override
    public void onHandleIntent(Intent intent) {
        Realm realm = Realm.getDefaultInstance();
        try {
            // go do some network calls/etc and get some data and stuff it into a 'json' var
            String json = customerApi.getCustomers();
            realm.beginTransaction();
            realm.createObjectFromJson(Customer.class, json); // Save a bunch of new Customer objects
            realm.commitTransaction();
            // At this point, the data in the UI thread is already up to date.
            // ...
        } finally {
            realm.close();
        }
    }
    // ...
}

Once the background service adds new customers to the Realm, the customers list is automatically updated in the UI without any additional intervention on your part. The same goes for individual objects. Suppose that you’re only managing one object. Just change it on one thread and the UI thread automatically has the new data. If you need to respond to that change, just add a listener like we’re doing above.

Using a Realm across threads

The only rule to using Realm across threads is to remember that Realm, RealmObject, and RealmResults instances cannot be passed across threads. Instead, use an asynchronous query or asynchronous transaction, to offload the operation to a background thread and bring any results back to the original thread for you.

When you want to access the same data from a different thread, you can obtain a new Realm instance (i.e. Realm.getInstance(RealmConfiguration config) or its cousins) and get your objects through a query.

The objects will map to the same data on disk, and will be readable and writeable from any thread.

Android framework threads

Be careful when working with these classes:

The AsyncTask class contains the doInBackground method which executes a background thread. The IntentService class contains the onHandleIntent(Intent intent) method which executes in a worker thread.

If you need to use Realm in either of these methods you should open the Realm, perform your work and then close the Realm before exiting. Below are a couple of examples.

AsyncTask

Open and close the Realm in the doInBackground method, as shown below.

private class DownloadOrders extends AsyncTask<Void, Void, Long> {
    protected Long doInBackground(Void... voids) {
        // Now in a background thread.

        // Open the Realm
        Realm realm = Realm.getDefaultInstance();
        try {
            // Work with Realm
            realm.createAllFromJson(Order.class, api.getNewOrders());
            Order firstOrder = realm.where(Order.class).findFirst();
            long orderId = firstOrder.getId(); // Id of order
            return orderId;
        } finally {
            realm.close();
        }
    }

    protected void onPostExecute(Long orderId) {
        // Back on the Android mainThread
        // do something with orderId such as query Realm
        // for the order and perform some operation with it.
    }
}

IntentService

ChangeListeners will not work in an IntentService. Even though it is a Looper thread, each invocation of onHandleIntent is a separate event that doesn’t “loop”. This means that it is possible to register change listeners, but they will never be triggered.

Open and close the Realm in the onHandleIntent method, as shown below.

public class OrdersIntentService extends IntentService {
    public OrdersIntentService(String name) {
        super("OrdersIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Now in a background thread.

        // Open the Realm
        Realm realm = Realm.getDefaultInstance();
        try {
            // Work with Realm
            realm.createAllFromJson(Order.class, api.getNewOrders());
            Order firstOrder = realm.where(Order.class).findFirst();
            long orderId = firstOrder.getId(); // Id of order
        } finally {
            realm.close();
        }
    }
}

Other libraries

This section describes how you can integrate Realm with other commonly used libraries for Android.

GSON

GSON is a library created by Google for deserializing and serializing JSON. GSON should work with Realm out of the box.

// Using the User class
public class User extends RealmObject {
    private String name;
    private String email;
    // getters and setters left out ...
}

Gson gson = new GsonBuilder().create();
String json = "{ name : 'John', email : '[email protected]' }";
User user = gson.fromJson(json, User.class);

You can also see an example of how GSON can work with Realm in our GridViewExample.

Serialization

For full compatibility with libraries like Retrofit you will often want to be able to both deserialize and serialize an object. Serializing Realm objects to JSON does not work with GSON’s default behavior as GSON will use field values instead of getters and setters.

To make GSON serialization work with Realm you will need to write a custom JsonSerializer for each object that can be serialized and register it as a TypeAdapter.

This Gist shows how it can be done.

Primitive lists

Some JSON APIs will return arrays of primitive types like integers or strings, which Realm doesn’t support yet. If it is not possible to change the JSON API, you can write a custom TypeAdapter for GSON that automatically maps between the primitive type from JSON and the wrapper object used by Realm.

In this Gist is an example of using a wrapper object for Integers, but the template can be used for all primitive arrays with datatypes supported by Realm.

Troubleshooting

Realm objects can contain fields that internally contain circular references. When this happens GSON can throw a StackOverflowError. We have seen this happen when a Realm object has a Drawable field:

public class Person extends RealmObject {
    @Ignore
    Drawable avatar;
    // other fields, etc
}

The Person class above contains an Android Drawable that has the @Ignore annotation applied. During GSON serialization the Drawable was being inspected and caused a StackOverflowError (GitHub Issue). To alleviate this, add the following code to your shouldSkipField method.

public boolean shouldSkipField(FieldAttributes f) {
  return f.getDeclaringClass().equals(RealmObject.class) || f.getDeclaringClass().equals(Drawable.class);
}

Please note the Drawable.class evaluation. This tells GSON to skip this field during serialization. Adding this will alleviate the StackOverflowError.

Jackson Databind

Jackson Databind is a library for binding JSON data to Java classes.

Jackson uses reflection to perform the data binding. This conflicts with Realm’s support for RxJava, as RxJava might not be available to the class loader. This can result in an exception that looks like this:

java.lang.NoClassDefFoundError: rx.Observable
at libcore.reflect.InternalNames.getClass(InternalNames.java:55)
...

This can be fixed by either adding RxJava to your project or create an empty dummy file that looks like the following.

package rx;

public class Observable {
    // Dummy class required for Jackson-Databind support if
    // RxJava is not a project dependency.
}

This issue has also been reported to the Jackson project here.

Kotlin

Realm is fully compatible with Kotlin programming language, but there are a few caveats to be aware of:

See this example for a working app combining Realm and Kotlin.

Parceler

Parceler is a library that automatically generates the boilerplate required to make an object respect the Parcelable interface. Due to Realm’s use of proxy classes, Parceler requires the following setup to work with Realm’s model classes.

// All classes that extend RealmObject will have a matching RealmProxy class created
// by the annotation processor. Parceler must be made aware of this class. Note that
// the class is not available until the project has been compiled at least once.
@Parcel(implementations = { PersonRealmProxy.class },
        value = Parcel.Serialization.BEAN,
        analyze = { Person.class })
public class Person extends RealmObject {
    // ...
}

If you are using Gradle for getting Parceler, please make sure the following lines are there (see here for more details):

compile "org.parceler:parceler-api:1.0.3"
apt "org.parceler:parceler:1.0.3"

There are some important restrictions to be aware of when using Parceler:

  1. If you model contains a RealmList you need to register a special adapter.
  2. Once an object has been parceled, it becomes detached from Realm and at this point behaves like an unmanaged object containing a snapshot of the data. Further changes to this object will not be persisted in Realm.

Retrofit

Retrofit is a library from Square that makes it easy to work with a REST API in a typesafe manner.

Realm will work with both Retrofit 1.* and 2.* out of the box, but note that Retrofit does not automatically add objects to Realm, instead you must manually add them using the realm.copyToRealm or realm.copyToRealmOrUpdate methods.

GitHubService service = restAdapter.create(GitHubService.class);
List<Repo> repos = service.listRepos("octocat");

// Copy elements from Retrofit to Realm to persist them.
realm.beginTransaction();
List<Repo> realmRepos = realm.copyToRealmOrUpdate(repos);
realm.commitTransaction();

Robolectric

Robolectric is a library that allows you to run JUnit tests directly in the JVM instead of in a phone or emulator. Currently, Robolectrics does not support native libraries like those that are bundled with Realm. This means that for now it is not possible to test Realm using Robolectric.

You can follow the feature request here: https://github.com/robolectric/robolectric/issues/1389

RxJava

RxJava is a [Reactive Extensions] library from Netflix that extends the [Observer pattern][obs-pat. It makes it possible to observe changes to data as composable sequences.

Realm has first-class support for RxJava. These Realm classes are Observable:

// Combining Realm, Retrofit and RxJava (Using Retrolambda syntax for brevity)
// Load all persons and merge them with their latest stats from GitHub (if they have any)
Realm realm = Realm.getDefaultInstance();
GitHubService api = retrofit.create(GitHubService.class);
realm.where(Person.class).isNotNull("username").findAllAsync().asObservable()
    .filter(persons.isLoaded)
    .flatMap(persons -> Observable.from(persons))
    .flatMap(person -> api.user(person.getGithubUserName())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(user -> showUser(user));

Asynchronous Queries are non-blocking—the code above will immediately return a RealmResults instance. If you want to ensure you’re only operating on a loaded list, filter the Observable via the filter operator and check the list by calling the [RealmResults.isLoaded](api/io/realm/RealmResults.html#isLoaded--) method. By checking to see if the `RealmResults` are loaded you can then determine if your query has completed or not.

See the RxJava sample project for more examples.

RxJava is an optional dependency, which means that Realm doesn’t automatically include it. This has the benefit that you can choose which version of RxJava to use as well as avoid the method count bloat in projects that does not use RxJava. RxJava has to be manually added to the build.gradle file.

dependencies {
  compile 'io.reactivex:rxjava:1.1.0'
}

It is possible to configure how Realm creates Observables by creating a custom RxObservableFactory. This is configured using RealmConfiguration.

RealmConfiguration config = new RealmConfiguration.Builder()
  .rxFactory(new MyRxFactory())
  .build()

If no RxObservableFactory is defined, Realm defaults to RealmObservableFactory which is a class provided by Realm that supports RxJava <= 1.1.*.

Testing and debugging

See our unitTestExample for information on how Realm can be combined with JUnit3, JUnit4, Robolectric, Mockito and PowerMock.

Android Studio debugging {#android studio debugging}

There’s a small “gotcha” to be aware of when working using Android Studio or IntelliJ: the debugger can provide misleading values depending on the debugging view you’re using.

For example, adding a watch in Android Studio on a RealmObject will display values of the fields. Unfortunately, these values are wrong because the field values are not used. Realm creates a proxy object behind the scenes and overrides the getters and setters in order to access the persisted data in the Realm. Adding a watch for any of the accessors will yield the correct values. See the image below: Android Studio, IntelliJ Debug RealmObject

In the image above, the debugger has stopped on line 113. There are three watch values, the person variable and the person.getName and person.getAge accessors. The code from lines 107 to 111 alters the person instance by changing the name and age. These values are then persisted in a transaction. On line 113, where the debugger is currently paused, the person watch instance is reporting on field values and they are incorrect. The watch values that use the accessor for person.getName and person.getAge report values that are correct.

Please note, the .toString method will output the correct values, but the watch panel will not (when watching a variable which is a RealmObject).

NDK debugging

Realm is a library that contains native code. We recommend that you use a crash reporting tool, such as Crashlytics, to track native errors so we are in a better position to help you if something goes wrong.

Debugging NDK crashes is usually cumbersome as the default stack trace provides minimal information that can be of use. Crashlytics will allow you to capture valuable NDK crash information. To enable NDK crash reporting in Crashlytics, please follow the steps outlined in this guide.

To enable NDK crash reporting for your project, add this to the root of your build.gradle file. Please note, the values androidNdkOut and androidNdkLibsOut are not needed.

crashlytics {
  enableNdk true
}

Current limitations

Realm generally tries to have as few constraints as possible, and we are continuously adding new features based on feedback from the community. However, Realm still has a few limitations. Please refer to our GitHub issues for a more comprehensive list of known issues.

Models

Realm models have no support for final and volatile fields. This is mainly to avoid discrepancies between how an object would behave as managed by Realm or unmanaged.

Realm model classes are not allowed to extend any other object than RealmObject. If declared, the default constructor (constructor with no parameters) must always be empty. The reason is that a default contructor will call methods which assume a Realm instance is present. But that instance isn’t create before the contructor returns. You can add other constructors for your convenience.

General

Realm aims to strike a balance between flexibility and performance. In order to accomplish this goal, realistic limits are imposed on various aspects of storing information in a Realm. For example:

  1. The upper limit of class names is 57 characters. Realm Java prepends class_ to all names, and the browser will show it as part of the name.
  2. The length of field names has a upper limit of 63 character.
  3. It is not possible to have two model classes with the same name in different packages.
  4. Nested transactions are not supported, and an exception is thrown if they are detected.
  5. Strings and byte arrays (byte[]) cannot be larger than 16 MB.
  6. Realm models have no support for final and volatile fields. This is mainly to avoid discrepancies between how an object would behave as managed by Realm or unmanaged.
  7. If a custom constructor is provided, a public no-arg constructor must also be present.
  8. Realm model classes are not allowed to extend any other class than RealmObject.

Sorting and querying on strings

Sorting and case-insensitive string matches in queries are only supported for character sets in Latin Basic, Latin Supplement, Latin Extended A, and Latin Extended B (UTF-8 range 0–591). Also, setting the case insensitive flag in queries when using equalTo, notEqualTo, contains, endsWith, beginsWith, or like will only work on characters from the English locale.

Realm uses non-standard sorting for upper and lowercase letters, sorting them together rather than sorting uppercase first. That means that '- !"#0&()*,./:;?_+<=>123aAbBcC...xXyYzZ is the actual sorting order in Realm. Read more about these limitations here.

Threads

Although Realm files can be accessed by multiple threads concurrently, you cannot hand over Realms, Realm objects, queries, and results between threads. The thread example shows how to use Realm in a multithreading environment. Read more about Realm’s threading.

Although Realm files can be accessed by multiple threads concurrently, they can only be accessed by a single process at a time. Different processes should either copy Realm files or create their own.

RealmObject’s hashCode

A RealmObject is a live object, and it might be updated by changes from other threads. Although two Realm objects returning true for RealmObject.equals must have the same value for RealmObject.hashCode, the value is not stable, and should neither be used as a key in HashMap nor saved in a HashSet.

Best practices

Out of the box, Realm works seamlessly with Android. The main thing that you have to keep in mind is that RealmObjects are thread confined. The importance of understanding this comes into play more when you want to start passing Realm objects between activities, to background services, broadcast receivers and more.

Preventing “Application Not Responding” (ANR) errors

Typically Realm is fast enough to read and write data on Android’s main thread. However, write transactions are blocking across threads so in order to prevent accidental ANR’s we advise that you perform all Realm write operations on a background thread (not Android’s main thread). Learn how to perform operations on the background thread via Realms Asynchronous Transactions.

Controlling the lifecycle of Realm instances

Choosing the proper lifecycle for a Realm instance is a balancing act. Because RealmObjects and RealmResults are accessed through a lazy cache, keeping a Realm instance open for as long as possible not only avoids the overhead incurred in opening and closing it but is likely to allow queries against it to run more quickly. On the other hand, an open Realm instance holds significant resources, some of which are not controlled by the Java memory manager. Java cannot automatically administer these resources. It is essential that code that opens a Realm instance closes it when it is no longer needed.

Realm uses an internal reference counted cache so that, after getting the first Realm instance, getting subsequent instances on the same thread is free. The underlying resources are released, though, only when all of the instances on that thread are closed.

One reasonable choice is to make the lifecycle of the Realm instance congruent with the lifecycles of views that observe it. The examples below demonstrate this using a Fragment and an Activity, each with a RecyclerView that displays data retrieved from a Realm instance. In both examples the Realm instance and the RecyclerView Adapter are initialized in the create method and closed in the corresponding destroy method. Note that this is safe, even for the Activity: the database will be left in a consistent state even if the onDestroy and close methods are never called.

Clearly, if most of the Fragments associated with an Activity require access to the same dataset, it would make sense for the Activity, not the individual Fragments, to control the lifecycle of the instance.

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

// onCreate()/onDestroy() overlap when switching between activities.
// Activity2.onCreate() will be called before Activity1.onDestroy()
// so the call to getDefaultInstance in Activity2 will be fast.
public class MyActivity extends Activity {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        realm = Realm.getDefaultInstance();

        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(this, realm.where(MyModel.class).findAllAsync()));

        // ...
    }

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

// Use onCreateView()/onDestroyView() for Fragments.
// Note that if the db is large, getting the Realm instance may, briefly, block rendering.
// In that case it may be preferable to manage the Realm instance and RecyclerView from
// onStart/onStop instead. Returning a view, immediately, from onCreateView allows the
// fragment frame to be rendered while the instance is initialized and the view loaded.
public class MyFragment extends Fragment {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        realm = Realm.getDefaultInstance();

        View root = inflater.inflate(R.layout.fragment_view, container, false);

        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(getActivity(), realm.where(MyModel.class).findAllAsync()));

        // ...

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.close();
    }
}

Reuse RealmResults and RealmObjects

On the UI thread and all other Looper threads, all RealmObjects and RealmResults are automatically refreshed when changes are made to the Realm. This means that it isn’t necessary to fetch those objects again when reacting to a RealmChangedListener. The objects are already updated and ready to be redrawn on the screen.

public class MyActivity extends Activity {

    private Realm realm;
    private RealmResults<Person> allPersons;
    private RealmChangeListener realmListener = new RealmChangeListener() {
        @Override
        public void onChange(Realm realm) {
            // Just redraw the views. `allPersons` already contain the
            // latest data.
            invalidateView();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realm = Realm.getDefaultInstance();
        realm.addRealmChangeListener(listener);
        allPerson = realm.where(Person.class).findAll(); // Create the "live" query result
        setupViews(); // Initial setup of views
        invalidateView(); // Redraw views with data
    }

    // ...
}

Auto-incrementing IDs

Auto-incrementing IDs are not supported by Realm by design. This is primarily because it is impossible to generate such keys in a distributed environment, and compatibility between data stored in a local Realm and a synchronized Realm is a high priority. Note that Realm does not need primary keys in order to create relationships.

It is still possible to efficiently create primary keys with Realm that satisfy the use cases provided by auto-incrementing IDs, but it is important to identify what the auto-incrementing ID is used for:

1) To provide a unique identifier in order to identify the object. This can be replaced by a GUID, which guarantees uniqueness and can be created by a device even when it’s offline:

```java
public class Person extends RealmObject {
    @PrimaryKey
    private String id = UUID.randomUUID().toString();
    private String name;
}
```

2) To provide loose insertion order. An example is sorting tweets. This can be replaced by a createdAt field, which doesn’t need to be a primary key:

```java
public class Person extends RealmObject {
    @PrimaryKey
    private String id = UUID.randomUUID().toString();
    private Date createdAt = new Date();
    private String name;
}
```

3) To provide strict insertion order. An example is a list of tasks. This can be modelled using a RealmList which will guarantee insertion order, even if devices have been offline.

```java
public class SortedPeople extends RealmObject {
    @PrimaryKey
    private int id = 0
    private RealmList<Person> persons;
}

public class Person extends RealmObject {
    private String name;
}

// Create wrapper object when creating object
RealmConfiguration config = new RealmConfiguration.Builder()
.initialData(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        realm.insert(new SortedPeople());
    }
});

// Insert objects through the wrapper
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        SortedPeople sortedPeople = realm.where(SortedPeople.class).findFirst();
        sortedPeople.getPersons().add(new Person());
    }
});
```

If you have a use case where you still think auto-incrementing IDs will be a better fit, you can use this helper class, but note that keys generated using this class are not usable if you:

1) Create Realm Objects in multiple processes. 2) Want to share the Realm between multiple devices at some point in the future.

For auto-incrementing IDs that are safe to create across processes, you will need to query for the max value each time you begin a transaction:

realm.beginTransaction();
Number maxValue = realm.where(MyObject.class).max("primaryKeyField");
long pk = (maxValue != null) ? maxValue + 1 : 0;
realm.createObject(MyObject.class, pk++);
realm.createObject(MyObject.class, pk++);
realm.commitTransaction();

Recipes

We’ve put together some recipes showing how to use Realm to accomplish a few specific tasks. We add more recipes regularly, so check back often. If there’s an example you’d like to see, please open an issue on GitHub.

FAQ

How can I find and view the content of my Realm file(s)?

This SO question describes where to find your Realm file. You can then view the content with our Realm Browser.

How big is the Realm Base library?

Once your app is built for release and split for distribution, Realm should only add about 800KB to your APK in most cases. The releases we distribute are significantly larger because they include support for more architectures (ARM7, ARMv7, ARM64, x86, MIPS). The APK file contains all supported architectures but the Android installer will only install native code for the device’s architecture. As a consequence, the installed app is smaller than the size of the APK file.

It is possible to reduce the size of the Android APK itself by splitting the APK into a version for each architecture. Use the Android Build Tool ABI Split support by adding the following to your build.gradle:

android {
    splits {
        abi {
            enable true
            reset()
            include 'armeabi-v7a', 'arm64-v8a', 'mips', 'x86', 'x86_64'
        }
    }
}

Select the architectures that you’d like to include and a separate APK will be built for each. See the Android Tools documentation about ABI Splits for more information.

An example is also included on GitHub.

If you don’t want to handle multiple APK’s it is also possible to restrict the number of architectures supported in a single APK. This is done by adding abiFilters to your build.gradle:

android {
    defaultConfig {
        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a', 'mips', 'x86', 'x86_64'
        }
    }
}

For more details about ABI splits and filters, read this article by Brijesh Masrani.

Is Realm open source?

Yes! Realm’s internal C++ storage engine and the language SDKs over it are entirely open source and licensed under Apache 2.0. Realm also optionally includes a closed-source Realm Platform Extensions component, but that is not required to use Realm as an embedded database.

What is the difference between a normal Java object and a Realm object?

The main difference is that a normal Java object contains its own data while a Realm object doesn’t contain data but get or set the properties directly in the database.

Instances of Realm objects can be either managed or unmanaged.

  • Managed objects are persisted in Realm, are always up to date and thread confined. They are generally more lightweight than the unmanaged version as they take up less space on the Java heap.
  • Unmanaged objects are just like ordinary Java objects, they are not persisted and they will not be updated automatically. They can be moved freely across threads.

It is possible to convert between the two states using Realm.copyToRealm and Realm.copyFromRealm.

Why do model classes need to extend RealmObject?

We need to add Realm specific functionality to your model classes. It also allows us to use generics in our APIs, making it easier to read and use. If you don’t want to extend a base class you can instead implement the RealmModel interface.

What are the RealmProxy classes about?

The RealmProxy classes are our way of making sure that the Realm object doesn’t contain any data itself, but instead access the data directly in the database.

For every model class in your project, the Realm annotation processor will generate a corresponding RealmProxy class. This class extends your model class and is what is returned when you call Realm.createObject(), but from the point of view of your code you won’t notice any difference.

Why do I need to use transactions when writing Realm objects?

Transactions are needed to ensure multiple fields are updated as one atomic operation. It allows you to define the scope of the updates that must be either fully completed or not completed at all (in case of errors or controlled rollback). By specifying the scope of the transaction you can control how frequent (or fast) your updates are persisted (i.e. insert multiple objects in one operation).

When doing inserts in a normal SQL based database like SQLite you are inserting multiple fields at once. This is automatically wrapped in a transaction, but is normally not visible to the user. In Realm these transactions are always explicit.

How do I handle out-of-memory exceptions?

Realm for Android is built upon an embedded storage engine. The storage engine does not allocate memory on the JVM heap but in native memory. When the storage engine cannot allocate native memory or the file system is full, Realm will throw an java.lang.OutOfMemoryError exception. It is important to not ignore this error. If your app continues running, accessing the Realm file might leave it in a corrupted or an inconsistent state. It is safest to terminate the app.

Large Realm file size

You should expect a Realm database to take less space on disk than an equivalent SQLite database.

In order to give you a consistent view of your data, Realm operates on multiple versions of a Realm. If you read some data from a Realm and then block the thread on a long-running operation while writing to the Realm on other threads, the version is never updated and Realm has to hold on to intermediate versions of the data which you may not actually need, resulting in the file size growing steadily. (This extra space would eventually be reused by future writes, or could be compacted, for example by calling compactRealm.)

I see a network call to Mixpanel when I run my app

Realm collects anonymous analytics when you run the Realm bytecode transformer on your source code. This is completely anonymous and helps us improve the product by flagging which version of Realm you use and what OS you use, and what we can deprecate support for. This call does not run when your app is running on your user’s devices — only when your source code is compiled. You can see exactly how & what we collect, as well as the rationale for it in our source code.

Couldn’t load “librealm-jni.so”

If your app uses other native libraries that don’t ship with support for 64-bit architectures, Android will fail to load Realm’s librealm-jni.so file on ARM64 devices. This is because Android cannot load 32-bit and 64-bit native libraries concurrently. The best solution would be to have all libraries provide the same set of supported ABIs, but sometimes that may not be doable if you are using a 3rd-party library. See VLC and Realm Library conflicts.

The workaround to this issue is to exclude Realm’s ARM64 library from the APK file by adding the following code to the app’s build.gradle. You can refer to Mixing 32- and 64-bit Dependencies in Android for more information.

android {
    //...
    packagingOptions {
        exclude "lib/arm64-v8a/librealm-jni.so"
    }
    //...
}

Also, there is a bug with Android Gradle Plugin 1.4.0 betas that leads it to improperly pack .so files included in jar files (see Realm Java issue 1421). To solve this problem, you can revert to Android Gradle Plugin 1.3.0 or use Android Gradle Plugin 1.5.0+.

We are aware of a number of 3rd party libraries, frameworks and management apps which do not have 64-bit support yet:

How do I backup and restore Realms?

Realms are stored in files on the file system. By calling the getPath you can get the full path of a Realm file. If you plan to back up or restore a Realm file this way, all instances of the Realm should be closed.

It is also possible to backup an open Realm file using realm.writeCopyTo.

If you want to backup a file to an external location like Google Drive. You can read this tutorial: part 1, part 2, and part 3.

Blackberry devices

Some Blackberry devices are capable of running Android apps. Unfortunately, the provided runtime environment is not complete, and we cannot guarantee compatibility. Known error messages include:

io.realm.exceptions.RealmFileException: Function not implemented in io_realm_internal_SharedRealm.cpp line 81 Kind: ACCESS_ERROR.

If you see issues with Blackberry devices, please consider to contribute a fix since both Realm Core and Realm Java are open source projects.

How to store and retrieve the encryption key used by Realm

Using Android KeyStore is probably the most secure way to store the Realm’s encryption key. Here is a recommended way to use it.

  1. Using Android’s KeyStore, generate an asymmetric RSA key, that will be stored/retrieved securely by Android. On version >= M the system requires user PIN (or finger print) to unlock the KeyStore, so even on rooted devices you have an extra layer of security.
  2. Generate a symmetric key (AES), that will be used to encrypt the Realm.
  3. Encrypt the symmetric AES key using your private RSA key.
  4. Now it’s safe to store the encrypted AES key on filesystem (in a SharedPreferences for example).
  5. When you need to use your encrypted Realm, retrieve your encrypted AES key, decrypt it using the public RSA key, then use it in the RealmConfiguration to open the encrypted Realm.

For an end-to-end example, look at our demo repositories:

Getting help

  • Need help with your code? Ask on StackOverflow. We actively monitor & answer questions on SO!
  • Have a bug to report? Open an issue on our repo. If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue.
  • Have a feature request? Open an issue on our repo. Tell us what the feature should do, and why you want the feature.
  • Love to follow what comes up next? Look at our changelog. The log shows the latest additions and changes we plan to release soon, and the history of how Realm has evolved.