Skill Level Intermediate
- [Instructor] When you want to save data on a device in an Android app, the first technology most developers use is SQLite. Support for SQLite is included in the Android SDK and Google provides plenty of support for using it in the form of helper APIs, documentation and examples. And the new architecture components that were introduced at Google I/O 2017 include the Room library that makes it easier than ever before to define a database structure and work with data in SQLite but there are other options for persistent storage in Android.
One of these is Realm, a data persistence library that makes it incredibly easy to store simple data persistently. Realm is available for a number of languages and platforms but in Android you'll use the version that's built for Java. The client-side version of Realm is free. There are other additions including a server side implementation that require a paid license but for simple Android client use, you can use the library without paying a license fee. You can find information about Realm on this website.
To get started in Realm, start with this simple starting app. It has a few buttons and two of them are labeled add data and query data. I'm going to show you how to integrate the Realm library into your project and then how to create Java classes that define the data structure of a Realm object. I'll then show you how to add objects to a Realm database and then how to query that information. In this project, I'll start in my Gradle build files.
I'll go to the project level file and I'll place the cursor after the class path for the Gradle plug-in. I'll add another class path declaration. This one will be io.realm: realm dash Gradle dash plugin and then a version number. As of the time of this recording, the most recent version was three dot five dot zero. So, now I've defined where the Gradle plug-in for this component will come from and next I'll go to the Gradle file for my app module.
I'll go to the top of the file, and after the existing apply directive I'll add another apply directive and this time it'll be apply plug-in and then again in single quotes realm dash Android. Then I'll re-sync my Gradle system. If everything works correctly, everything should come back without any error messages. The Realm library is now a part of the project and I can start using the library's classes, interfaces and annotations.
To define a data structure, create a POJO class, a plain old Java object that has properties with setters and getters. In the project window I'll go to my base package and I'll create a new sub package which I'll name data. Then in the data package, I'll create a new Java class which I'll name dog and I'll set the super class as something called Realm object. Because I've integrated the Realm library into my project, this and other classes are available.
It's io.realm.RealmObject. Next, I'll define the structure of this class and again, this is the same as any POJO class. This class will have three fields. They'll all be private and the first one will be an integer that I'll name dog ID. The second will be a string that I'll call name and the third will be another integer that I'll call age. Now, I'm going to mark the first field as a primary key and you do that with a Realm annotation named primary key.
Now, the primary key field will act just like it does in a standard database. There can now only be one object in the database with a particular primary key value. Next, I'll add a couple of constructor methods. You need a no arguments constructor. I'll generate that from the menu and in the Choose Fields dialog I'll click on select none and that creates the no arguments version. Then I'll generate another constructor and this time I'll look for all three values, the ID, the name and the age.
Next, I'll create a few getters and setters. Once again I'll use the code generation feature, I'll choose getter and setter, I'll select all fields and click OK and down here at the bottom I'll create a to string method. Code generate to string and you can customize this as you like to show the information the way you want but this is how it will be displayed when I log the information in my application. So again, this looks like any POJO class.
The difference is that it extends Realm object and that it uses the primary key annotation to indicate how unique values will be managed. Now, I'll go to my main activity class. In order to work with Realm you need something called a Realm object. I'll declare a private field and I'll set its type as Realm from io.realm and I'll name it Realm. Now I'll go to the onCreate method and in this method, I'll initialize the Realm database with Realm.init and I'll pass in this as the context.
Then I'll initialize the Realm object that I declared at the top with realm equals Realm.getDefaultInstance. There are other ways of initializing the Realm object. This one will give you the reference to the default instance for this application but it is possible to create more than one Realm database within a particular app. Now I'm ready to add data to the Realm database. I'll do this in the add data method. You always work with Realm with transactions.
You begin a transaction, you take certain actions that add, remove or update information and then you commit the transaction. I'll start with realm.beginTransaction. Then I'll use realm.copyToRealm and this takes an instance of a Realm object or a Realm model. I'll create a new instance of my dog class and I'll pass in three values, one for the ID, Scruffy for the name and eight for the age.
Then I'll duplicate that line and I'll change the ID to two, the name to Minnie and the age to three. Finally, after taking all of these actions, I'll call realm.CommitTransaction. Now, because there can be exceptions, you should always wrap this sort of code in a try catch block. So, I'll select all of that code and then I'll go to code, Surround With, and choose try catch. And in the catch block, I'll specifically look for an exception named Realm primary constraint exception.
This is the exception that will be thrown if you try to add an object that's already been added to the database with the same ID. If you get that constraint exception, you should back out the transaction that's currently in effect, and you can do that with Realm.CancelTransaction. So, now whenever the user clicks on add data, the data will be added to the database, and I'll note that by first calling clear log. I'll pass in null and that will clear the output on the screen, and then I'll call the log method and pass in a value of data added to Realm.
And I'll run the code. I'll click add data and I see the message that the data's been added. Now, I'll query the data, and I'll do this code in this method named query data. I'll create an instance of a Java collection. This is the collection class from Java.util. There's also a collection class that's apart of Realm but I recommend using the Java version. I'll set the type as dog and that's the name of my POJO class. I'll name the collection dogs, and I'll get its value with this syntax realm.where.
Next, I'll pass in the class that's going to be retrieved. With dog.class and then after all that, I'll call a method named find all, and this will return the data in the order in which it was stored in the database. Then I'll use a for each loop. The type of the object I'll be looking at is dog and the name will be dog. The collection I'm looking at is dogs and for each item in the collection, I'll call the log method and pass in dog.toString.
Then I'll stop the app completely and run it again in my emulator. When the app appears, I'll click query data and I'll see that the data is returned. Now clear the log and query the data again, and there's the data in the order in which it was added to the database. Now, the important thing here is that I stopped the app and then ran it again and then queried the data without adding the data again, and that proves that the data was stored persistently between application sessions.
Now there are a lot of things you can do when you're querying the data, and here's one simple example. After I call the find all method, I'll add a call to a method named sort, and I'll pass in the name of a field on which I want to sort. This can either be a public field or as is the case in my class, a private field with setters and getters. Notice that there are a number of different versions of this method. I'm using the simplest one. I'll run the application again. I'll clear the log and query the data and this time the data is returned in the order of the age field with the youngest dog first.
So, that's how you can get started, very easily, with Realm, a data persistence library that let's you store and query data with a remarkably small amount of code. You can find plenty of examples of different ways to structure, persist and query data using Realm at the Realm website at Realm.io.
Q: Why can't I earn a Certificate of Completion for this course?
A: We publish a new tutorial or tutorials for this course on a regular basis. We are unable to offer a Certificate of Completion because it is an ever-evolving course that is not designed to be completed. Check back often for new movies.