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();

The method Realm.getInstance() creates the database file if it has not been created, otherwise opens the file. The RealmConfiguration object controls all aspects of how a Realm is created - whether it’s an inMemory() database, name of the Realm file, if the Realm should be cleared if a migration is needed, initial data, etc.

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 background threads, it’s very important to close the Realm instance(s) once it’s no longer used (for example, transaction is complete and the thread execution ends). Failure to close all Realm instances on background thread results in version pinning, and can cause a large growth in file size.

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

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

It’s worth noting that above API Level 19, you can replace this code with just this:

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

Models

Next step would be creating your models. Here a question might be asked, “what is a model?”. A model is a structure which defines properties of an object being stored in the database. For example, in the following we model 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 & setter
    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;
    }
}

Note that your models should extend RealmObject class. Primary key is also specified by @PrimaryKey annotation. Primary keys can be null, but only one element can have null as a primary key. Also you can use the @Ignore annotation for the fields that should not be persisted to the disk:

@Ignore
private String isbn;

Inserting or updating data

In order to store a book object to your Realm database instance, you can first create an instance of your model and then store it to the database via copyToRealm method. For creating or updating you can use copyToRealmOrUpdate. (A faster alternative is the newly added insertOrUpdate()).

// Creating an instance of the model
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);
    }
});

Note that all changes to data must happen in a transaction. Another way to create an object is using the following pattern:

Book book = realm.createObject(Book.class, primaryKey);
...

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