Realm A New Database For Mobile Devices

Posted By : Akash Tomer | 12-Jan-2018

All android developer know about the term SQLite, an internal database to store the information. But the has changed now a new database comes to replace it called Realm.The realm is a mobile database for android and ios devices. It does not use the SQLite engine and made it C++ core. It basically follows OO pattern.It provides data faster than SQLite, easily creates table and store data. The only disadvantage with this database is that it cannot access object across the thread.

First of all, you have to add the dependency in your build gradle file.

compile 'io.realm:realm-android:0.82.1'

Create the realm instance to get access of the database.

Realm realm = Realm.getInstance(this);

You can also set the configuration of database by using the below code.

RealmConfiguration objRealmConfiguration = new RealmConfiguration.Builder(this)
                .name(Realm.DEFAULT_REALM_NAME)
                .schemaVersion(0)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm.setDefaultConfiguration(objRealmConfiguration);

Now create the student class and extend it with real object.

public class Studen extends RealmObject {
    private String name;
    private int age;

    // ... Generated getters and setters ...
}

Now if you want to insert the data into database you can insert like this

realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setAge(18);
realm.commitTransaction();

Now you want to find all record with name peter and john you can query like this

RealmQuery<User> query = realm.where(Student.class);
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");
RealmResults<User> result1 = query.findAll();
RealmResults<User> result2 = realm.where(User.class)
                                  .equalTo("name", "John")
                                  .or()
                                  .equalTo("name", "Peter")
                                  .findAll();

If you want to delete the record 

RealmResults<Student> results = realm.where(Book.class).findAll();
                 Student b = results.get(position);
                String title = b.getName();
                realm.beginTransaction();
                results.remove(position);
                realm.commitTransaction();

 

Hope this will help you.

Best of luck!

About Author

Author Image
Akash Tomer

Akash is an Android Developer at Oodles Technology.

Request for Proposal

Name is required

Comment is required

Sending message..