Navigation

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
   }
}

Prerequisites

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.

Procedure

A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 minutes

1

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.

2

Create an Atlas cluster.

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

Important

You must deploy the Atlas cluster with MongoDB version 3.4 or later.

The Sync features require 3.6 or later.

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.

3

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.

1

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.

2

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": "%%user.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 (%%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 MongoDB Rules.

3

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 filter rule, 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 }
Filter Query { "owner_id": "%%user.id" }

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

Click the Save button to save your changes.

Note

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 filters, see MongoDB Filters.

C. Set Up Authentication

Estimated Time to Complete: ~10 minutes per service

1

Add authentication information in MongoDB Stitch.

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

Facebook

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:

        com.mongodb.stitch.sdk.examples.todo
        
      • For Default Activity Class Name, enter:

        com.mongodb.stitch.sdk.examples.todo.MainActivity
        
    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"
            android:value="@string/facebook_app_id"/>
        

      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:

    https://stitch.mongodb.com/api/client/v2.0/auth/callback
    
  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.

Google

A. Set up an app in Google Cloud Platform:

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
      

      Tip

      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:

      com.mongodb.stitch.sdk.examples.todo
      

      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:

      https://stitch.mongodb.com
      
    • For Authorized redirect URIs, enter the following:

      https://stitch.mongodb.com/api/client/v2.0/auth/callback
      
  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 Authentication Providers.

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

1

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.
2

Update project with your MongoDB Stitch App ID.

From the Project view:

  1. Go to the todo/src/main/assets folder and open the stitch.properties 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.

3

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"
        android:value="@string/facebook_app_id"/>
    

If using Google authentication, no additional configuration is required.

4

Review MongoDB Stitch connection logic in application source file.

In the onCreate method of the MainActivity.java 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.

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(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,
          "mongodb-atlas");

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

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

_remoteCollection.sync().configure(
      DefaultSyncConflictResolvers.remoteWins(),
      new MyUpdateListener(),
      new MyErrorListener());

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

5

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 use the default selection.
    2. Click Next.
    3. Click Download on one of the recommended system images. You may need to agree to the terms.
    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.