Navigation

Read & Write Data - Android SDK

On this page

Note

The examples on this page use the data model of a project management app that has two Realm object types: Project and Task. A Project has zero or more Tasks.

See the schema for these two classes, Project and Task, below:

A read from a realm generally consists of the following steps:

All query, filter, and sort operations return a results collection. The results collections are live, meaning they always contain the latest results of the associated query.

Important
Synchronous Reads and Writes on the UI Thread

By default, you can only read or write to a realm in your application's UI thread using asynchronous transactions. That is, you can only use Realm methods whose name ends with the word Async in the main thread of your Android application unless you explicitly allow the use of synchronous methods.

This restriction exists for the benefit of your application users: performing read and write operations on the UI thread can lead to unresponsive or slow UI interactions, so it's usually best to handle these operations either asynchronously or in a background thread. However, if your application requires the use of synchronous realm reads or writes on the UI thread, you can explicitly allow the use of synchronous methods with the following SyncConfiguration options:

Tip

To find an object with a specific primary key value, open a realm and query the primary key field for the desired primary key value using the RealmQuery.equalTo() method:

The first step of any read is to get all objects of a certain type in a realm. With this results collection, you can operate on all instances on a type or filter and sort to refine the results.

Example

In order to access all instances of Project and Task, use the where() method to specify a class:

A filter selects a subset of results based on the value(s) of one or more object properties. Realm Database provides a full-featured query engine you can use to define filters. The most common use case is to find objects where a certain property matches a certain value. Additionally, you can compare strings, aggregate over collections of numbers, and use logical operators to build up complex queries.

Example

In the following example, we use the query engine's comparison operators to:

  • Find high priority tasks by comparing the value of the priority property value with a threshold number, above which priority can be considered high.
  • Find just-started or short-running tasks by seeing if the progressMinutes property falls within a certain range.
  • Find unassigned tasks by finding tasks where the assignee property is equal to null.
  • Find tasks assigned to specific teammates Ali or Jamie by seeing if the assignee property is in a list of names.

A sort operation allows you to configure the order in which Realm Database returns queried objects. You can sort based on one or more properties of the objects in the results collection.

Realm Database only guarantees a consistent order of results when the results are sorted.

Example

The following code sorts the projects by name in reverse alphabetical order (i.e. "descending" order).

All write operations to a realm must occur within a write transaction. For more information about how to perform a write transaction, see Write Transactions.

Important
Realm Object Writes are File Writes

Whenever you create, update, or delete a Realm object, your changes update the representation of that object in Realm Database and emit notifications to any subscribed listeners. As a result, you should only write to Realm objects when necessary to persist data.

Important
Synchronous Reads and Writes on the UI Thread

By default, you can only read or write to a realm in your application's UI thread using asynchronous transactions. That is, you can only use Realm methods whose name ends with the word Async in the main thread of your Android application unless you explicitly allow the use of synchronous methods.

This restriction exists for the benefit of your application users: performing read and write operations on the UI thread can lead to unresponsive or slow UI interactions, so it's usually best to handle these operations either asynchronously or in a background thread. However, if your application requires the use of synchronous realm reads or writes on the UI thread, you can explicitly allow the use of synchronous methods with the following SyncConfiguration options:

Instantiate Realm objects as you would any other object. In a transaction, you can add the object to the realm if the realm's schema includes the object type. When you add an instance to the realm, it becomes managed by that realm.

With the Java and JavaScript SDKs, instead use the realm's factory method in a transaction to instantiate your class. This automatically inserts the instance into the realm.

Example

This code demonstrates how to create an object with createObject():

You can also insert objects into a realm from JSON. Realm supports creating objects from String, JSONObject, and InputStream types. Realm ignores any properties present in the JSON that are not defined in the Realm object schema.

Example

This code demonstrates how to create a single object from JSON with createObjectFromJson() or multiple objects from JSON with createAllFromJson():

Within a transaction, you can update a Realm object the same way you would update any other object in your language of choice. Just assign a new value to the property or update the property.

Example

This code changes the turtle's name to "Archibald" and sets Archibald's age to 101 by assigning new values to properties:

An upsert is a write operation that either inserts a new object with a given primary key or updates an existing object that already has that primary key. We call this an upsert because it is an "update or insert" operation. This is useful when an object may or may not already exist, such as when bulk importing a dataset into an existing realm. Upserting is an elegant way to update existing entries while adding any new entries.

Example

This code demonstrates how to upsert an object with realm. We create a new turtle enthusiast named "Drew" and then update their name to "Andy" using insertOrUpdate():

You can also use copyToRealmOrUpdate() to either create a new object based on a supplied object or update an existing object with the same primary key value. Use the CHECK_SAME_VALUES_BEFORE_SET ImportFlag to only update fields that are different in the supplied object:

Example

This code demonstrates how to insert an object or, if an object already exists with the same primary key, update only those fields that differ:

Realm Database supports collection-wide updates. A collection update applies the same update to specific properties of several objects in a collection at once.

Example

The following code demonstrates how to update a collection. Thanks to the implicit inverse relationship between the Turtle's owner property and the TurtleEnthusiast's turtles property, Realm Database automatically updates Josephine's list of turtles when you use setObject() to update the "owner" property for all turtles in the collection.

Because realm collections always reflect the latest state, they can appear, disappear, or change while you iterate over a collection. To get a stable collection you can iterate over, you can create 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.

Iterator objects created from RealmResults use snapshots automatically. Iterator objects created from RealmList instances do not use snapshots. Use RealmList.createSnapshot() or RealmResults.createSnapshot() to manually generate a snapshot you can iterate over manually:

Example

The following code demonstrates how to iterate over a collection safely using either an implicit snapshot created from a RealmResults Iterator or a manual snapshot created from a RealmList:

To delete an object from a realm, use either the dynamic or static versions of the deleteFromRealm() method of a RealmObject subclass.

Important
Do not use objects after delete

Realm Database throws an error if you try to use an object after it has been deleted.

Example

The following code shows how to delete one object from its realm with deleteFromRealm():

To delete an object from a realm, use the deleteAllFromRealm() method of the RealmResults instance that contains the objects you would like to delete. You can filter the RealmResults down to a subset of objects using the where() method.

Example

The following code demonstrates how to delete a collection from a realm with deleteAllFromRealm():

Sometimes, you have dependent objects that you want to delete when you delete the parent object. We call this a chaining delete. Realm Database does not delete the dependent objects for you. If you do not delete the objects yourself, they will remain orphaned in your realm. Whether or not this is a problem depends on your application's needs.

Currently, the best way to delete dependent objects is to iterate through the dependencies and delete them before deleting the parent object.

Example

The following code demonstrates how to perform a chaining delete by first deleting all of Ali's turtles, then deleting Ali:

Realm Database supports deleting all instances of a Realm type from a realm.

Example

The following code demonstrates how to delete all Turtle instances from a realm with delete():

It is possible to delete all objects from the realm. This does not affect the schema of the realm. This is useful for quickly clearing out your realm while prototyping.

Example

The following code demonstrates how to delete everything from a realm with deleteAll():

Give Feedback

On this page