Introduction to Realm: Why you don’t SQLite anymore?

Introduction to Realm: Why you don’t SQLite anymore?

By | April 1st, 2016
No Comments on Introduction to Realm: Why you don’t SQLite anymore?

A deeper look at the SQLite replacement that is being used widely by the

industry


														
							

Configuration: How to set it up?
CRUD: Create, Read, Update, Delete
Create

You can add your own constructors in Realm as long as you have one default constructor.
• Get an instance of the Realm class
• Begin a transaction
• Create the object
• Set the required properties whose values will be persisted
• Commit the transaction

Refer to SNIPPET 3 from HERE http://dgit.in/RealmCode Instead of using the copyToRealm method which adds a new entry time, you can also use the copyToRealmOrUpdate method which inserts if the item does not exist and updates the item otherwise. It however requires your model to have a primary key. Another way of performing the insert would be as follows.
Refer to SNIPPET 4 from HERE http://dgit.in/RealmCode

Read

Read operations don’t block each other and don’t require transactions. They use a FLUENT interface with the help of which you can define conditions on which objects you would like to read.

Read All

Refer to SNIPPET 5 from HERE http://dgit.in/
RealmSnippets The RealmResults object contains those Drop objects that satisfy some condition. In our case we have not specified any condition and thereby retrieve all the objects of type Drop stored in Realm. We can iterate over RealmResults like a simple ArrayList and process the data further.

Read all drops made by the person ‘abc@gmail.com’

Use the equalTo method to specify the values which you would like to match for a particular field. Refer to SNIPPET 6 from HERE http://dgit.in/
RealmCode

Update

Update looks similar to any other write operation. Here are the following steps to perform an update

• Get an instance of the Realm class
• Begin the transaction
• Modify the object.
• Commit the transaction.

Update the email of the Person from ‘abc@gmail.com’ to ‘def@gmail.com’

In the snippet below, we simply locate the first Person object whose email is ‘abc@gmail.com’ and update its value with the help of a setter method inside a transaction. If there are more than one people with the email ‘abc@gmail.com’ we would simply use the findAll method instead of findFirst which returns a RealmResults. We can loop through the RealmResults and call the setter method on each object. Refer to SNIPPET 7 from HERE http://dgit.in/
RealmCode

Delete

If you wish modify or delete any of the objects in a RealmResults, you must do so in a write transaction. Here are the steps to delete an item permanently from Realm.

• Get an instance of the Realm class
• Begin the transaction
• Delete one or more objects.
• Commit the transaction

Refer to SNIPPET 8 from HERE http://dgit.in/
RealmCode

Transactions: How to persist changes?

In Realm, all write operations (adding, modifying, and removing objects) must be wrapped in write transactions. A write transaction can either be committed or cancelled. During the commit, all changes will be written to disk, and the commit will only succeed if all changes can be persisted. By cancelling a write transaction, all changes will be discarded. Using write transactions, your data will always be in a consistent state.

Synchronous

So far we wrote synchronous transactions which can also be written in a different way. Instead of manually keeping track of realm.beginTransaction(), realm.commitTransaction(), and realm. cancelTransaction() you can use the realm. executeTransaction() method, which will automatically handle begin/commit, and cancel if an error happens. Let’s take our earlier example of adding a drop to Realm and use a transaction block for the same.
Refer to SNIPPET 9 from HERE http://dgit.in/
RealmCode

Asynchronous

By using an asynchronous transaction, Realm will run that transaction on a background thread and report back when the transaction is done. Use the overloaded executeTransaction method that takes one more parameter known as Callback which has two methods: onSuccess and onError where we can execute code depending on the outcome of the transaction.
Refer to SNIPPET 10 from HERE http://dgit.in/
RealmCode

Queries: How to do operations on data?

Realm’s query engine uses a Fluent interface to construct multi-clause queries. Queries in Realm are lazy in the sense that actual data is not copied unless it is needed.

Operators

We executed some pretty basic queries earlier like trying to find the person whose email is ‘abc@gmail.com’ Lets explore the operators in more depth.
Refer to SNIPPET 11 from HERE http://dgit.in/
RealmCode
Some operators that you can use in place of contains would be between(), greaterThan(), lessThan(), greaterThanOrEqualTo(), lessThanOrEqualTo(), equalTo(), notEqualTo(), contains(), beginsWith() & endsWith() along with logical operators such as and(), or() and not() Instead of using equals which compares all the text in the email to match with ‘gmail’, we use the contains clause which means gmail can be present anywhere in the email field.

Sorting

We can easily sort the list of emails which we retrieved in the previous step by calling the sort method on the RealmResults object. Use the sort method which accepts the name of the field on the basis of which items are sorted in the ascending order by default. Refer to SNIPPET 12 from HERE http://dgit.in/RealmCode

Aggregating values

Realm also lets you aggregate results and obtain the minimum, maximum, average or sum of all values for a field. In our case, if the Person model class had a field called age, we could perform the following operations.
Refer to SNIPPET 13 from HERE http://dgit.in/RealmCode

Iterating

There are several ways of iterating through the RealmResults obtained after performing a query. Don’t forget to use a transaction if you plan on updating any or all of the Person objects.
Refer to SNIPPET 14 from HERE http://dgit.in/RealmCode

Synchronous & Asynchronous Queries

The queries we executed so far run on the UI thread. Given that Realm loads data lazily and Realm uses a highly efficient structure to store and retrieve data, synchronous queries perform pretty fast compared to SQLite. To run a query asynchronously, we first create the query and use the findAllAsync method instead of the regular findAll method.

Refer to SNIPPET 15 from HERE http://dgit.in/RealmCode
The query is not blocking and immediately returns a RealmResults<Drop>. This is a promise similar to the concept of Future in standard Java. The query will continue to run in a background thread, and once it completes it will update the returned instance of RealmResults. If you want to be notified when the query completes and the RealmResults object is updated, you can register a RealmChangeListener. This listener will be called every time the RealmResults are updated to reflect the latest changes in the Realm. You can only use asynchronous queries on a Looper thread.

Refer to SNIPPET 16 from HERE http://dgit.in/RealmCode

In the final step, simply register and unregister for the listener inside your Activity or Fragment to prevent memory leaks.
Refer to SNIPPET 17 from HERE http://dgit.in/RealmCode

Advanced Concepts

Several advanced concepts in Realm dealing with its configuration, encryption, notifications, json processing and multithreading are covered in detail here. (https://realm.io/docs/java/latest/#realms)

Conclusion

Realm is a free product as of March 16, 2016 and has been in use since 2012 in commercial apps for both Android and IOS. It has a growing community with 24×7 support available on its GitHub repo for the most common difficulties you will encounter. It accelerates development time compared to SQLite while being truly cross-platform in nature.

Links

Java documentation for Realm https://realm.io/docs/java/latest/ If you want to learn more on how to use realm in a practical android application, check the complete bucket drops series which covers it https://goo.gl/WvX8GD

Go to Page: 1 2

Google
Nash David
Nash David is passionate about technology and mobile devices. He closely follows the smartphone, and tablet platform market. He also leads editorial efforts for devworx. You may send him tweets @nashpd or email editor@devworx.in
@