Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

CRUD - Delete - Java SDK

On this page

  • About the Examples on this Page
  • 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
  • Delete an Object Using an Iterator

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:

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

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


Do not use objects after delete

The SDK throws an error if you try to use an object after it has been deleted.

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 example 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 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 example demonstrates how to perform a chaining delete by first deleting all of Ali's turtles, then deleting Ali:

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

The following example 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.

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

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.

For an example, refer to Iteration.

← Update