Updated 27 November 2017
In this blog we are going to cover up read and write operation on Realm Database. Realm is another type of database in Android. But, what is very important, Realm doesn’t use Sqlite and realm is very fast, you are even allowed to write the data in UI thread.Realm stores instances of this class as objects. It’s not an SQL database, it’s a NoSQL database.
Installation:
Step 1: Add the class path dependency to the project level build.gradle file.
1 2 3 4 5 6 7 8 |
buildscript { repositories { jcenter() } dependencies { classpath "io.realm:realm-gradle-plugin:4.2.0" } } |
Step 2: Apply the realm-android plugin to the top of the application level build.gradle file.
1 |
apply plugin: 'realm-android' |
Enabling Realm Mobile Platform: Before your application can synchronize with the Realm Object Server, it has to be enabled in your build file. Add this to the application’s build.gradle:
1 2 3 |
realm { syncEnabled = true; } |
Initializing Realm:
Before you can use Realm in your app, you must initialize it. This only has to be done once. You must provide an Android context. A good place to initialize Realm is in onCreate on an application
1 2 3 4 5 6 |
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this) .name(Realm.DEFAULT_REALM_NAME) .schemaVersion(0) .deleteRealmIfMigrationNeeded() .build(); Realm.setDefaultConfiguration(realmConfiguration); |
To use your object as a Realm object you have to simply extend RealmObject class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class RealmModel extends RealmObject { private String firstName; private String lastName; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } } |
Realm Write Operation:
1 2 3 4 5 6 |
Realm realm=Realm.getDefaultInstance(); realm.beginTransaction(); RealmModel realmModel=realm.createObject(RealmModel.class); realmModel.setFirstname("Hello"); realmModel.setLastname("World"); realm.commitTransaction(); |
To get data from the Realm Database:
1 2 3 |
RealmResults<RealmModel> realmModels=realm.where(RealmModel.class).findAll(); String fName=realmModel.getFirstname(); String lName=realmModel.getLastname(); |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.