Read & Write Data - Java SDK
On this page
- About the Examples on this Page
- Read from Realm Database
- Find a Specific Object by Primary Key
- Query All Objects of a Given Type
- Filter Queries Based on Object Properties
- Sort Query Results
- Query a Relationship
- Query an Inverse Relationship
- Aggregate Data
- Write Operations
- Create a New Object
- Modify an Object
- Upsert an Object
- Update a Collection
- Iteration
- Delete an Object
- Delete Multiple Objects
- Delete an Object and its Dependent Objects
- Delete All Objects of a Specific Type
- Delete All Objects in a Realm
About the Examples on this Page
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:
Read from Realm Database
A read from a realm generally consists of the following steps:
- Get all objects of a certain type from the realm.
- Optionally, filter the results using the query engine.
- Optionally, sort the results.
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.
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:
Find a Specific Object by Primary Key
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:
Query All Objects of a Given Type
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.
In order to access all instances of ProjectTask
and Project
, use
the where() method
to specify a class:
Filter Queries Based on Object Properties
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.
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.
Sort Query Results
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.
The following code sorts the projects by name in reverse alphabetical order (i.e. "descending" order).
Query a Relationship
Query an Inverse Relationship
Aggregate Data
Write Operations
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.
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.
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:
Create a New Object
Use realm.createObject() in a transaction to create a persistent instance of a Realm object in a realm. You can then modify the returned object with other field values using accessors and mutators.
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.
This code demonstrates how to create a single object from JSON with createObjectFromJson() or multiple objects from JSON with createAllFromJson():
Modify an Object
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.
This code changes the turtle's name to "Archibald" and sets Archibald's age to 101 by assigning new values to properties:
Upsert an Object
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.
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:
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:
Update a Collection
Realm Database supports collection-wide updates. A collection update applies the same update to specific properties of several objects in a collection at once.
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.
Iteration
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:
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
:
Delete an Object
To delete an object from a realm, use either the dynamic or static
versions of the deleteFromRealm()
method of a RealmObject subclass.
Realm Database throws an error if you try to use an object after it has been deleted.
The following code shows how to delete one object from its realm with deleteFromRealm():
Delete Multiple Objects
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.
The following code demonstrates how to delete a collection from a realm with deleteAllFromRealm():
Delete an Object and its Dependent Objects
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.
The following code demonstrates how to perform a chaining delete by first deleting all of Ali's turtles, then deleting Ali:
Delete All Objects of a Specific Type
Realm Database supports deleting all instances of a Realm type from a realm.
The following code demonstrates how to delete all Turtle instances from a realm with delete():
Delete All Objects in a Realm
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.
The following code demonstrates how to delete everything from a realm with deleteAll():