Basic Usage

suggest change

Setting up an instance

To use Realm you first need to obtain an instance of it. Each Realm instance maps to a file on disk. The most basic way to get an instance is as follows:

// Create configuration
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context).build();

// Obtain realm instance
Realm realm = Realm.getInstance(realmConfiguration);
// or
Realm.setDefaultConfiguration(realmConfiguration);
Realm realm = Realm.getDefaultInstance();

Realm.getInstance() creates the database file if it does not exist, and opens it otherwise. The RealmConfiguration object controls how a Realm is created: whether it is an inMemory() database, the file name, whether the Realm is cleared when a migration is needed, initial data, and so on.

Please note that calls to Realm.getInstance() are reference counted (each call increments a counter), and the counter is decremented when realm.close() is called.

Closing an instance

On a background thread, close every Realm instance when you are finished with it (for example, after the transaction, before the thread ends). Leaving one open pins old versions and the file can grow without bound.

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Realm realm = null;
        try {
            realm = Realm.getDefaultInstance();
            // ...
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }
};

new Thread(runnable).start(); // background thread, like `doInBackground()` of AsyncTask

From API 19, the same close-on-exit pattern can be written with try-with-resources, because Realm implements Closeable:

try (Realm realm = Realm.getDefaultInstance()) {
    // ...
}

Models

The next step is to create your models. A model is the structure of an object stored in the database. The following class models a book.

public class Book extends RealmObject {
 
    // Primary key of this entity
    @PrimaryKey
    private long id;
 
    private String title;

    @Index // faster queries
    private String author;
 
    // Standard getters and setters
    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getAuthor() {
        return author;
    }
 
    public void setAuthor(String author) {
        this.author = author;
    }
}

Models extend RealmObject, and @PrimaryKey marks the primary key. A String primary key may be null, but only one object can have a null primary key. A primitive long, as in this model, cannot be null. Use @Ignore for fields that should not be written to disk:

@Ignore
private String isbn;

Inserting or updating data

To store a book, create a model instance and save it with copyToRealm. copyToRealmOrUpdate inserts or updates. insertOrUpdate() is a faster alternative.

// Creating an instance of the model
final Book book = new Book();
book.setId(1);
book.setTitle("Walking on air");
book.setAuthor("Taylor Swift");

// Store to the database
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        realm.insertOrUpdate(book);
    }
});

All writes must happen inside a transaction. createObject is another way to create an object, and it also has to run inside a transaction:

Book book = realm.createObject(Book.class, 1L);
...

Querying the database

RealmResults<Book> results = realm.where(Book.class).findAll();
RealmResults<Book> results = realm.where(Book.class)
                                  .greaterThan("id", 10)
                                  .findAll();
RealmResults<Book> results = realm.where(Book.class)
                                  .beginGroup()
                                      .equalTo("author", "Taylor Swift")
                                      .or()
                                      .contains("author", "Peter")
                                  .endGroup().findAll();

Deleting an object

For example, we want to delete all books by Taylor Swift:

// Start of transaction
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // First Step: Query all Taylor Swift books
        RealmResults<Book> results = ...
        
        // Second Step: Delete elements in Realm
        results.deleteAllFromRealm();
    }
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents