Docs Menu

Docs HomeAtlas App Services

Xamarin (Android & iOS) Tutorial

On this page

  • Overview
  • Prerequisites
  • Start with the Template
  • Set up the Template App
  • Open the App
  • Explore the App Structure
  • Run the App
  • Check the Backend
  • Modify the Application
  • Add a New Property
  • Set the Priority when Creating a New Item
  • Run and Test
  • Update the subscription
  • Run and Test
  • Update Flexible Sync on the Server
  • Test the changes
  • Conclusion
  • What's Next?

Realm provides a .NET SDK that allows you to create a multi-platform mobile application with Xamarin and C#. This tutorial is based on the .NET Flexible Sync Template App, named xamarin.todo.flex, which illustrates the creation of a Todo application. This application enables users to:

  • Register their email as a new user account.

  • Sign in to their account with their email and password (and sign out later).

  • View, create, modify, and delete tasks.

This tutorial adds on to the Template App. You will add a new Priority field to the existing Item model and update the Flexible Sync subscription to only show items within a range of priorities.

Depending on your experience with Xamarin, this tutorial should take around 30 minutes.


Check Out the Quick Start

If you prefer to get started with your own application rather than follow a guided tutorial, check out the .NET Quick Start. It includes copyable code examples and the essential information that you need to set up an Atlas App Services backend.

  • Ensure that you have the necessary software installed. Select the tab for your development environment:

  • You need previous experience deploying a Xamarin app to an Android Emulator, iOS Simulator, and/or a physical device.

  • This tutorial starts with a Template App. You need an Atlas Account, an API key, and realm-cli to create a Template App.

    • You can learn more about creating an Atlas account in the Atlas Getting Started documentation. For this tutorial, you need an Atlas account with a free-tier cluster.

    • You also need an Atlas API key for the MongoDB Cloud account you wish to log in with. You must be a Project Owner to create a Template App using realm-cli.

    • To learn more about installing realm-cli, see Install realm-cli. After you have installed realm-cli, login using the API key for your Atlas project.

This tutorial is based on the .NET Flexible Sync Template App named "xamarin.todo.flex". We start with the default app and build new features on it.

If you already have the latest Realm CLI installed, you can run the realm-cli apps create command to set up the backend and create the Xamarin base app. The following command creates a new app based on the xamarin.todo.flex template. The app is created in a development environment, is named "MyTutorialApp", and is deployed in the US-OR region:

realm-cli apps create -n MyTutorialApp --template xamarin.todo.flex \
--deployment-model global --location us-or --environment development

To learn more about the Template Apps, and to install the Template App that this tutorial uses in the Atlas App Services UI, see Template Apps.


Navigate to the directory where the Realm CLI created the template app and open the realm-todo-app.sln solution in Visual Studio.


In Visual Studio, take a few minutes to explore how the solution is organized. This is a standard multi-platform solution, based on a template provided by Visual Studio, that has been modified for our specific use. The solution has 3 projects:


Provides shared resources, including the view pages and the Item model that represents the Realm object we will store in the database.

To learn more about how Realm Object Schemas are used in .NET applications, see Realm Objects in our .NET client guide.

Contains Android-specific resources, such as the Toolbar formatting.
Contains iOS-specific resources.

You will perform all of the steps in this tutorial within the shared realm-tutorial-dotnet project. Specifically, you will be working in the following files:

Item.cs (in the Models folder)
Defines the Realm object we store in the database.
Provides the functionality for viewing, updating, and deleting items in the user's todo list.
NewItemPopup.xaml and NewItemPopup.xaml.cs
Provides the functionality to add a new item to the list.

Without making any changes to the code, you should be able to run the app in either the Android emulator or the iOS Simulator, or on a physical device. When you installed the template app, the Realm CLI also set up a new backend for you and populated the realm.json file with the correct app ID.

Run the app, register a new user account, and then add a new Item to your todo list.


Log in to Atlas App Services. In the Atlas tab, click on Browse Collections. In the list of databases, find and expand the todo database, and then the Item collection. You should see the document you created in this collection.


Now that you have confirmed everything is working as expected, we can add changes. In this tutorial, we have decided that we want to add a "Priority" property to each Item so that we can filter Items by their priorities. The Priority property will be mapped to a PriorityLevel enum to constrain the possible values.

To do this, follow these steps:

  1. Expand the realm-todo-dotnet project.

  2. Expand the Models folder and open the Item class file.

  3. Add the following public property:

    public int? Priority { get; set; }
  4. Also add a PriorityLevel enum below the Item class:

    public enum PriorityLevel
    Severe = 0,
    High = 1,
    Medium = 2,
    Low = 3
  1. In NewItemPopup.xaml.cs, add a new public property under the existing ItemName and IsOK properties:

    public string ItemName { get; set; }
    public bool IsOK { get; set; }
    public int Priority { get; set; }
  2. Open the NewItemPopup.xaml file. This file defines the UI element for creating a new Item. We will add two UI elements: a label and a Picker that enables the user to choose which priority level to set on the new Item. Locate the OK button, and insert the following code above it:

    <Label FontSize="18" HorizontalTextAlignment="Left" Text="Priority:"/>
    <Picker x:Name="newItemPriority">
  3. Now switch back to the NewItemPopup.xaml.cs file. Find the OK_Button_Clicked event handler, which currently sets the ItemName and IsOK properties. Add a line to also set the Priority property:

    this.Priority = newItemPriority.SelectedIndex;


    Using SelectedIndex

    Because we ordered the priorities in the Picker element from highest to lowest, the lower the selected item's index, the higher that Item's priority is: 0 for Severe, 1 for High, etc. Therefore, the index matches the PriorityLevel enum values.

  4. Finally, open the ItemPage.xaml.cs file, and find the Popup_Popped event handler, which fires when the NewItemPopup is closed. In this method, we create a new Item and save it to the realm. Where we set the other Item properties, add a line of code to set the new Priority property:

    var newItem = new Item()
    OwnerId = _user.Id.ToString(),
    Summary = popup.ItemName,
    IsComplete = false,
    Priority = popup.Priority

At this point, you can run the application again. Log in using the account you created earlier in this tutorial. You will see the one Item you previously created. Add a new Item, and you will see that you can now set the priority. Choose High for the priority and save the Item.

Now switch back to the Atlas data page in your browser, and refresh the Item collection. You should now see the new Item with the priority field added and set to 1. You will also notice that the existing Item now also has a priority field, and it is set to null, as shown in the following screenshot:

Two items in a collection


Why Didn't This Break Sync?

Adding a property to a Realm object is not a breaking change and therefore does not require a client reset. The template app has Development Mode enabled, so changes to the client Realm object are reflected in the server-side schema. For more information, see Development Mode and Update Your Data Model.


In the ItemPage.xaml.cs file, we define the Flexible Sync subscription that defines which documents we sync with the user's device & account. Find the AddSubscriptionsToRealm method. Within the subscriptions.Update() method, you can see that we are currently subscribing to all documents where the OwnerId property matches the authenticated user. We want to maintain that, but only sync Items that are marked as High or Severe priority.

As you may recall, the Priority field is of type int, where the highest priority ("Severe") has a value of 0, and the lowest priority ("Low") has a value of 3. We can make direct comparisons between an int and the Priority property. To do so, edit the LINQ statement to include documents where the priority is equal to or less than PriorityLevel.High (or 1), as shown here:

subscriptions.Update(() =>
var defaultSubscription = _itemsRealm.All<Item>()
.Where(t => t.OwnerId == _user.Id
&& t.Priority <= (int)PriorityLevel.High

Run the application again. Log in using the account you created earlier in this tutorial. You would expect to see the Item you most recently created, since it has a priority of "High" (1). But it is not in the list. If you check your application logs, you will see an entry that looks something like this:

"Client provided query with bad syntax: unsupported query for table "Item":
key "priority" is not a queryable field" (error_code=300, query_version=1)

This message tells us that we have added a field to our subscription without configuring Flexible Sync to use that field.

  1. Switch back to the Atlas page in your browser. Select the Atlas App Services tab and open the app you are using.

  2. In the left-hand navigation, choose Device Sync, and then click OK in the dialog box about Development Mode being enabled.

  3. Scroll down to the Select Queryable Fields section. In the dropdown labeled Select or create a queryable field, choose "priority". The priority field will be added to the fields shown:

    Priority field is now queryable.
  4. Save your changes.


Return to your mobile app. To ensure the subscription is re-run, log out the current user, and then log in again. After an initial moment when Realm resyncs the document collection, you will see the new Item of High priority that you created.

If you want to further test the functionality, you can create Items of various priorities. You will see that a new Item with a lower priority briefly appears in the list of Items and then disappears. Realm creates the Item locally, syncs it with the backend, and then filters out the Item because it doesn't meet the subscription rules.

You'll note, too, that the document you initially created is not synced, because it has a priority of null. If you want this Item to be synced, you can edit the document in the Atlas UI and add a value for the priority field, or you can change your subscription to include documents with null values:

subscriptions.Update(() =>
var defaultSubscription = _itemsRealm.All<Item>()
.Where(t => t.OwnerId == _user.Id
&& (t.Priority == null || t.Priority <= 1));


Priority as Int

If you compare this subscription with the one above, you'll note we specify the Priority as <= 1, which is the same as comparing against the PriorityLevel enum casted to an int.

Adding a property to an existing Realm object is a non-breaking change, and Development Mode ensures that the schema change is reflected server-side. If you add or change a subscription to use an additional field, whether newly added or previously existent, you need to modify the Flexible Sync settings to enable querying against that field.


Give Feedback

How did it go? Use the Give Feedback tab at the bottom right of the page to let us know if this tutorial was helpful or if you had any issues.

←  Android With Kotlin TutorialReact Native Tutorial →
Give Feedback
© 2022 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.