Mounika calls herself a dynamic professional with expertise in developing mobile applications for iOS and Android. With C# and Xamarin as primary areas of expertise, she also likes to dwell in doodle art in her pastime.
For enquiries call:
+1-469-442-0620
When it comes to mobile applications with database support, the first thing that comes to mind is SQLite. However, there are a few drawbacks with SQLite such as no support for data encryption and low performance when dealing with large data.
In this article, we take a closer look at Realm, a non-relational database and a solid replacement for SQLite and core data. It is quite efficient and works seamlessly even with a large amount of data.
Why use Realm
Ways of using Realm
In this article I will show how to integrate realm in the Xamarin Forms project. I will also show how to use realm as local database(Part-1) and realm cloud(Part-2)
Prerequisites
Part-1: Using Realm Local Database
Go to PCL project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml
Go to Android project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml
Go to iOS project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml
Add the below code in the file
FodyWeavers.xml
<? xml version="1.0" encoding=" utf-8" ?> < Weavers> <RealmWeaver /> </Weavers>
Let's create a model
public class Animals: RealmObject { public string Name { get; set; } public int Age { get; set; } }
Opening Realms
Opening a Realm can be done by instantiating a new Realm object.
// Get a Realm instance var realm = Realm.GetInstance();
Note: If nothing is passed, it creates the default realm. You can add realm name as below
var realm = Realm.GetInstance(“Animals”);
This will create realm db with “Animals” name
To add/delete/update or do any operation of realm, first you need a Realm instance.
1) Add elements
var _realm = Realm.GetInstance(); Add elements _realm.Write(() => { var entry = new Todo{ Name = “Dog”, Age =3 }; _realm.Add(entry); });
2) Delete elements
var param = _realm.All<Animals>().First(b => b.Name == “Dog”); using (var trans = _realm.BeginWrite()) { _realm.Remove(param); trans.Commit(); }
3) Update elements
_realm.Write(() => { param.Name = “Cat”; _realm.Add(param); });
Part-2: Using Realm Cloud
Now let's see how to use realm cloud. The setup is still the same. Here we need a few more additional steps.
1) Create an account in realm cloud at.
(one-month free trial account).
2) Create an instance in realm cloud by clicking on create an instance
This instance ID will be further used for authentication
There are two types of Realm sync
Here I am going to show you how to use full sync as Realm recommends using Full sync.
Client Authentication:
Realm supports two types of authentication
The below code shows how to use simple authentication with username and password.
var authUrl = new Uri("https://myinstance.cloud.realm.io"); var credentials = Credentials.UsernamePassword(username, password, createUser: false); var user = await User.LoginAsync(credentials, authUrl);
To authenticate, you must supply a server URL. This is the base URL for your server, such as https://myinstance.cloud.realm.io
Note: Here “myinstance" would be the instance id that you generated while creating your account
Create Realm through realm studio or through code. If the realm has not been created, while calling the realm instance it will automatically create. If you have already created through realm studio, you can just call the instance.
Example:
public static string realmPath = "realms://instanceId/realmname;
Here the realm path consists of instanceId followed by realm name. Something like this
public static string realmPath = "realms://instanceId/Animals;
Now let’s login and call realm instance
public async Task GetInitialize() { await StartLoginCycle(); } private async Task StartLogin() { do { await Task.Yield(); } while (!await LogIn()); }
//Call the login method
private async Task<bool> LogIn() { try { user = User.Current; if (user == null) { var username = "DevUser"; //Pass your username var password = “User123"; //Pass the password var credentials = Realms.Sync.Credentials.UsernamePassword(username, password); /// Log in as the user. user = await User.LoginAsync(credentials, new Uri(RealmConnectionString.AuthUrl)); } Debug.Assert(user != null); Console.WriteLine("Login successful."); await GetDataFromRealm(); return true; } catch (Exception ex) { ///await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); return false; } }
//Call or create realm instance:
public static async Task GetDataFromRealm()
{ var configuration = new FullSyncConfiguration(new Uri(realmPath, UriKind.Absolute), user); Var _realm = await Realm.GetInstanceAsync(configuration); var param = _realm.All<Animals>(); //Adding/updating/deleting operations are same as above }
Conclusion
In the above sections, we have seen how to integrate realm local db and realm cloud into your xamarin forms project. You will also be able to perform operations like adding items, updating items and deleting items (showed in Part-1). These code snippets are the same for realm local database and realm cloud.
You can find how to use linq queries in the below reference link. However, few features are not supported such as: groupby, union, intersect, distinct,except, select, selectmany, join, group join, concat, skipwhile, take, skip and takewhile.
Note: Opening the realm instance asynchronously for the first time is recommended. Once the data is synchronized, the instance should be called synchronously.
You can also download realm studio, create a realm file, and add the data. This helps to minimize the code in your application.
Below are a few reference links that might help with further information