Realm for Android
Posted By : Sobraj Yumkhaibam | 25-Mar-2016
As the trend for new and latest trends in software development rises to an exponential level, it's always good to get hold of something better than the normal existing trend. A piece of the latest trends is the Realm for Android. I haven't used it extensively but in a few apps i have tried it and i find it much better and way more cool than the SQLite database.
The tutorial with Realm v0.84.1.
1. Adding Realm to a Project
Add the following compile dependency in the app module’s build.gradle file.
|
1
|
compile 'io.realm:realm-android:0.84.1' |
2. Creating a Realm
A Realm seems indifferent to a SQLite database. It has an associated file, that will persist on Android’s file system once it's created.
To create a new Realm, the static Realm.getInstance method is called from inside any Activity.
|
1
|
Realm myRealm = Realm.getInstance(context); |
Note that a Realm file called default.realm is created when calling Realm.getInstance,without a RealmConfiguration is passed to it.
To add another Realm to the app, use aRealmConfiguration.Builder object and give the Realm file a unique name.
|
1
2
3
4
5
6
|
Realm myOtherRealm = Realm.getInstance( new RealmConfiguration.Builder(context) .name("myNextRealm.realm") .build()); |
3. Creating a RealmObject
A JavaBean can be stored in a Realm when it extends the RealmObject class. Instances of the following class is easily stored in a Realm:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class Country extends RealmObject { private String name; private int population; public Country() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; }} |
To use a member variable of a RealmObject as a primary key, use the @PrimaryKey annotation. For example, adding a primary key called code to the Country class:
|
01
02
03
04
05
06
07
08
09
10
|
@PrimaryKeyprivate String code;public String getCode() { return code;}public void setCode(String code) { this.code = code;} |
4. Creating Transactions
Writing data to Realm is slightly more complex. Realm is ACID compliant and so as to ensure atomicity and consistency, Realm forces you to execute all write operations inside a transaction. The beginTransaction method is used to start a new transaction. To end the transaction, use the commitTransaction method.Here’s an example to create and save an instance of the Country class:
|
01
02
03
04
05
06
07
08
09
10
11
|
myRealm.beginTransaction(); // Create an object Country country1 = myRealm.createObject(Country.class); // Set its fields country1.setName("India"); country1.setPopulation(51658008); country1.setCode("NO");myRealm.commitTransaction(); |
Notice that country1 was not created using the constructor of theCountry class. To manage an instance of a RealmObject, the createObject method must be used to create the instance.
If the constructor must be used, use the copyToRealm method of the associated Realm object before the transaction is committed. For example:
|
1
2
3
4
5
6
7
8
9
|
// Create the objectCountry country2 = new Country();country2.setName("Australia");country2.setPopulation(146430430);country2.setCode("AUS");myRealm.beginTransaction(); Country copyOfCountry2 = myRealm.copyToRealm(country2);myRealm.commitTransaction(); |
5. Writing Queries
To create a query, the where method of the relevant Realm object is used and the class of the objects we are interested in, is passed. After creating the query, we can fetch all results using the findAll method, which returns a RealmResults object. In the following example, we fetch and print all objects of type Country:
|
1
2
3
4
5
6
7
8
|
RealmResults<Country> results1 = myRealm.where(Country.class).findAll();for(Country c:results1) { Log.e("results1", c.getName());}// Prints India, Australia |
To filter the results, Realm offers several methods, such as beginsWith, endsWith,lesserThan and greaterThan. The following code tells how to use the greaterThan method to fetch only those Countryobjects whose population is greater than 500 million:
|
1
2
3
4
5
6
|
RealmResults<Country> results2 = myRealm.where(Country.class) .greaterThan("population", 50000000) .findAll();// Gets only India |
If the results of the query are to be sorted, use the findAllSortedmethod. It takes a String specifying the name of the field to sort by and a boolean specifying the sort order as its arguments.
|
1
2
3
4
5
6
|
// Sort in descending order of nameRealmResults<Country> results3 = myRealm.where(Country.class) .findAllSorted("name", false);// Gets India, Australia |
Conclusion
In this small article, i've provided a glimpse of how Realm can be implemented in Android. To know more about it, refer its Java documentation.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sobraj Yumkhaibam
Sobraj has been developing Android applications for a while now and is expert in mobile application development . He excels in developing mobile applications with location based intelligence. He loves Modelling as a hobby.