ToDo (Android App)

This tutorial demonstrates how to use MongoDB Stitch to integrate the following services into an Android mobile app:

This tutorial builds a ToDo Android application. The ToDo application maintains a list of todo items for each user. Users can log in using their existing Google or Facebook credentials, add items to their list, check completed items, and delete completed items. The items are stored in the local MongoDB Mobile database and kept in sync with Atlas whenever the app is online.

The ToDo app uses the items collection in the todo database, and stores one document per each todo item. A todo item has the following format:

   _id : ObjectId("5be2118cc6eda6d1671ddee3"),
   owner_id : ObjectId("5be1158f4ffdc28344840ae4"),
   text : "Put your right foot in.",
   checked : true,
   __stitch_sync_version : {
      spv : 1,
      id : "c73dd901-bba3-44ab-bf49-9b8abc99c7d1",
      v : 3


For this app, you need the following:

  • A MongoDB Atlas cluster using MongoDB version 3.4+. This tutorial uses an Atlas Free Tier cluster.
  • A developer account with either Google or Facebook (or both) for user authentication services.
  • Access to the Android Studio IDE.


A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 minutes


Log into Atlas.

To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.


Create an Atlas cluster.

If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.

Atlas provides a Free Tier M0 replica set as well as paid M10+ clusters. Free Tier deployments have restrictions as compared to paid M10+ deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier), M2, and M5 Limitations.


Add a MongoDB Stitch application.

  1. In Atlas, click Stitch Apps in the left-hand navigation.
  2. Click the Create New Application button.
  3. Under Application Name, enter a name for your application. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  4. Under Link To Cluster, select the MongoDB Atlas cluster that you’d like to use for your application.
  5. Click Create.

After you click Create, a new Stitch application will be created for you. The application will include a MongoDB service named mongodb-atlas that is linked to your cluster. This process may take several minutes.

Once your application has been created, you will be automatically redirected to the Stitch application console.

B. Define Rules

Estimated Time to Complete: ~6 minutes

MongoDB Stitch rules specify the read and write access for the fields in your collections.


Configure MongoDB.

Create a namespace for the todo.items collection:

  1. Click on Rules under Atlas Clusters in the left navigation pane.

  2. Click the + Add Collection button.

  3. In the Add New Collection dialog, provide the following values:

    Property Value
    Database Name todo
    Collection Name items
    Select a Template Users can only read and write their own data
    Field Name For User ID owner_id

    Stitch creates a new rule (a combination of a role and permissions) based on the template. This rule allows an authenticated user to only read and write their own documents and to insert new documents.

  4. Click Add Collection.

MongoDB Authorization

MongoDB Stitch rules do not override the read and write access (i.e. authorization) that may have been set up separately in MongoDB. That is, MongoDB Stitch rules determine whether the fields are readable or writable; not whether the client has authorization to read or write to a particular database or collection.

Similarly, MongoDB Stitch validation rules do not override document validation rules set up separately in MongoDB.


Review Rules for Documents in todo.items.

To view the rule associated with the template, expand todo, and then click on items. Click on the edit button ( pencil icon ) to open the role editor.

By default, the collection has the following Apply When rule:

  "owner_id": ""

With this rule, read and write operations can access all fields in a document if the document contains an owner_id field whose value equals the user ID ( of the client issuing the read. If the owner_id field in the document does not equal the client user id, the document is not readable.

For more information on MongoDB rules, see the rules section of the MongoDB service overview.


Add a Filter for todo.items.

Filters improve performance by filtering the results returned from a MongoDB call. To add a filter, click on the Filters tab.

To create a query filter, click the Filters tab, and then click the + New Filter button. Click the filter 1 header to expand it, and then provide the following values:

Field Value
Apply When { "%%true": true }
Query Filter { "owner_id": "" }

This filter indicates that when %%true equals true (i.e. always), return only the documents where the owner_id field matches the

Click the Save button to save your changes.


Adding this filter is optional, because it duplicates the logic in the rules that were added with the template we chose. However, in a large-scale application, this filter improves performance significantly.

For more information on MongoDB rules, see the query filters section of the MongoDB service overview.

C. Set Up Authentication

Estimated Time to Complete: ~10 minutes per service


Add authentication information in MongoDB Stitch.

In the Users section in MongoDB Stitch, enable Facebook and Google.


A. Set up an app in Facebook:

  1. Log in to your Facebook Developer account. If you do not have a Facebook developer account, see Facebook - Register and Configure an App. You will also need to create a regular Facebook account if you do not already have one.

  2. Add a new Facebook application.

  3. Once created, your application view opens to Product Setup. If not, go to your newly added app and click Add Product.

  4. In Product Setup, click Get Started for Facebook Login. The screen should display the Quickstart instructions.

  5. Choose Android for your platform.

  6. In the Quick Start for Android:

    1. You can skip the Download the Facebook SDK for Android step and the Import the Facebook SDK step as the ToDo android app project covers these steps.

    2. For Tell Us about Your Android Project step, enter the following:

      • For Package Name, enter:

      • For Default Activity Class Name, enter:

    3. Click Save. You may be prompted to verify the Google Play Package Name since your app is not listed publicly on Google Play. Click Use this package name.

    4. Continue to the next step.

    5. Generate the development key hash per instructions and save in the Key Hashes field and continue.

    6. Optional. You can enable/disable Single Sign On and continue to the next step.

    7. Note the following entries for your project file:

      • facebook_app_id and fb_login_protocol_scheme to copy into your project’s strings.xml file in a later step.

        <string name="facebook_app_id">012345678900000</string>
        <string name="fb_login_protocol_scheme">fb1234985978493875</string>
      • meta-data entry to copy into your project’s AndroidManifest file in a later step.

        <meta-data android:name="com.facebook.sdk.ApplicationId"

      You will use these entries during the setup step of the ToDo Android project in this tutorial.

    8. You can omit the remaining steps as they are already incorporated into the ToDo Android project.

  7. Click Settings under Facebook Login in the left-hand navigation menu.

  8. Under Valid OAuth redirect URIs, add the following entry:
  9. Save changes.

  10. Click Settings for your application (i.e. not the Settings under Facebook Login). Note the App ID and App Secret. You will use the information in the Users section of the MongoDB Stitch Admin Console.

B. Configure Stitch for Facebook Authentication:

  1. Select Users from the left-side navigation.
  2. Select the Providers tab.
  3. Select Users from the left-side navigation.
  4. For Facebook, click the Edit button.
  5. In the Facebook provider settings:
    • Switch the Provider Status toggle to enabled.
    • Enter your new Facebook App ID in the Client ID field and Facebook App Secret in Client Secret field.
  6. Click Save.


A. Set up a project in the Google API Console:

For Google authentication, you must create both Android client credentials and web client credentials.

  1. Create a new set of Google OAuth credentials for your application (see Setting up OAuth 2.0 for details).

  2. Go to your project view and click API Manager.

  3. Click Credentials.

  4. To create the Android client credentials, Create credentials, and select OAuth client ID. You may be prompted to configure the consent screen. If so, add the product name and click Save.

  5. When creating the OAuth client ID:

    • For Application Type, select Android.

    • For Name, enter a name to associate with the client ID.

    • For Signing-certificate fingerprint, enter the SHA1 fingerprint. To generate the SHA1 fingerprint, run the following command in a terminal or Windows Command Prompt:

      keytool -exportcert -alias androiddebugkey -keystore <path to debug.keystore> -list -v

      Terminal example:

      keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

      Windows Command Prompt example:

      keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore -list -v


      If using debug.keystore, the password is android.

      Enter the SHA1 fingerprint. For more information and an example, see Google Setting up OAuth 2.0 Help page

    • For Package name, enter the following:


      The package name may be found in the ToDo Android application project’s AndroidManifest.xml

  6. Click Create.

  7. To create the Web app client credentials, Create credentials, and select OAuth client ID.

    • For Application Type, select Web application.

    • For Name, enter the name you want to associate with this client ID.

    • For Authorized JavaScript origins, enter the following:
    • For Authorized redirect URIs, enter the following:
  8. Click Create.

  9. Note the Web app client ID and secret. You will use the information in the Users section of the MongoDB Stitch Admin Console.

B. Configure Stitch Admin Console for Google Authentication:

  1. Select Users from the left-side navigation.
  2. Select the Providers tab.
  3. For Google, click the Edit button.
  4. In the Google provider settings:
    • Switch the Provider Status toggle to enabled.
    • Enter your new Client ID and Client Secret from the google Web App client credentials.
  5. Click Save.

For details on all authentication methods supported by Stitch, see User Authentication Overview.

D. Download the Application Source Code

Estimated Time to Complete: ~2 minutes

Download the MongoDB Stitch github example repository and unzip it. The source code for the ToDo Android application can be found in todo/android directory.

E. Configure and Run the Application

Estimated Time to Complete: ~5 minutes


Open the project in Android Studio.

  1. Open Android Studio.
  2. Select Open an existing Android Studio project.
  3. Navigate to the downloaded example directory and open todo/android.

Update project with your MongoDB Stitch App ID.

From the Project view:

  1. Go to the todo/src/main/assets folder and open the file.

  2. Update the appId with your MongoDB Stitch app id and save.

    In the MongoDB Stitch console, you can find your App ID in the Clients view.

  3. Go to the todo/src/main/res/values folder and open the strings.xml file.

  4. Update the stitch_client_app_id with your MongoDB Stitch app id and save.


Update project with your Facebook App ID.

If using Facebook authentication, from the Project view:

  1. Go to the todo/src/res/values folder and open the strings.xml.

    Add your facebook_app_id entry and update the fb_login_protocol_scheme entry. The entries are listed in step 6 in the Facebook Login Quickstart.

    <string name="facebook_app_id">012345678900000</string>
    <string name="fb_login_protocol_scheme">fb1234985978493875</string>
  2. Go to the manifests folder and open the AndroidManifest.xml. Add your facebook meta-data entry inside the <application> block. The entry is listed in step 6 in the Facebook Login Quickstart.

    <meta-data android:name="com.facebook.sdk.ApplicationId"

If using Google authentication, no additional configuration is required.


Review MongoDB Stitch connection logic in application source file.

In the onCreate method of the file, we instantiate a StitchAppClient object and establish a connection to the Stitch app. We then instantiate a RemoteMongoClient to work with the mongodb-atlas Atlas service.

protected void onCreate(Bundle savedInstanceState) {

      _handler = new Handler();
      _refresher = new ListRefresher(this);

      this._client = Stitch.getDefaultAppClient();
      this._client.getAuth().addAuthListener(new MyAuthListener(this));

      _mongoClient = this._client.getServiceClient(RemoteMongoClient.factory,

The onCreate method then instantiates a RemoteMongoCollection and configures the Sync capabilities:

_remoteCollection = _mongoClient.getDatabase("todo").getCollection("items");

      new MyUpdateListener(),
      new MyErrorListener());

For more information on building an app that uses Sync, see MongoDB Mobile.


Run the todo app.

  1. Click Run.

  2. If no virtual device is available, click Create New Virtual Device.

    1. Select the Phone device for your app. You can select any of the deviuce definitions.

    2. Click Next.

    3. On the System Image tab, you are presented with a list of Recommended images, all of which are x86-based. You must switch to the Other Images tab to see the full list of images, including those platforms supported by Stitch. Select one of the supported platforms (an ARM32, ARM64, or x86_64 device that is running an armeabi-v7a, arm64-v8a, or x86_64 image of Android 5.0 or later), and, if neccessary, click Download to download the image.

      Default images

      The list of Recommended images only contains x86 images, which Stitch does not support. You must switch to the Other Images tab to see the full list of images.

    4. Click Finish.

  3. Select the virtual device from the Available Virtual Devices.

  4. Click OK.

  5. Wait for the device to come online.

  6. Sign in using Google or Facebook or anonymous login.