Navigation

ToDo (Android App)

This tutorial demonstrates how to use MongoDB Stitch to integrate the following services for an Android application:

  • Google/Facebook user authentication services
  • MongoDB service

This tutorial incorporates the services into a provided ToDo android application. The ToDo application is an application that maintains a single-user todo list. Users can log in using Google or Facebook credentials, add items to the list, check completed items and delete completed items.

The ToDo app uses the items collection in the todo database, which stores a document per each todo item.

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

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. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  3. Select your Atlas cluster for your MongoDB service.
  4. Click Create.

Upon creation of your app, you will be redirected to the MongoDB Stitch console. Your app is created with a MongoDB service named mongodb-atlas.

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 the MongoDB service.

  1. Click on the MongoDB service mongodb-atlas.

  2. In the Rules tab, click the New button and add the following collection:

    Database: todo

    Collection: items

    Note

    You must add rules for each collection the MongoDB service accesses.

The application saves documents to the collection. Each document in the todo.items collection has the form:

{
  "_id" : <ObjectID>,
  "text" : <string>,      // ToDo item.
  "owner_id" : <string>,  // Corresponds to the user logged into the app.
  "checked" : <boolean>   // Optional.  Only appears if the user checks the item in the app.
}
2

Review the rules for todo.items collection.

Click on todo.items to view the read rules, write rule, the validation rule, and the filter rule.

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.

Read Rule

To view the read rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following read rule for the top-level document:

{
  "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, no field in the document is readable.

For more information on MongoDB read rules, see MongoDB Service Read Rule.

Write Rule

To view the write rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following write rule for the top-level document:

{
  "owner_id": "%%user.id"
}

With this rule, the write operation must result in a document where the owner_id equals the user ID of the client issuing the write. If the value of owner_id does not match the client user ID, MongoDB Stitch blocks the write.

Modify the write rule to the following and click Save:

{
  "%or": [
    { "%%prevRoot.owner_id": "%%user.id" },
    { "%%prevRoot": { "%exists": 0 } }
  ]
}

%%prevRoot references the original document before the write operation. This rule requires that either:

  • The document to be modified by the write operation contains an owner_id field that equals the id of the user logged in to the ToDo app (%%user.id), or
  • The document to be modified by the write operation did not exist; i.e. the write operation results in an insert operation.

For more information on MongoDB write rules, see MongoDB Service Write Rule.

Validation Rule

To view a validation rule, click on the owner_id in the Field Rules view.

By default, the collection has the following validation rule specified on the owner_id field that determines whether a write operation is permissible:

{
  "%or": [
    { "%%prev": "%%user.id" },
    { "%%prev": { "%exists": false } }
  ]
}

With this rule, a write operation is valid if either:

  • The write operation modifies a document where the value of owner_id previous to the write operation (%%prev) equals the user ID (%%user.id) of the client issuing the write. An example of this kind of write operation is a client modifying a document that it previously inserted, or
  • The write operation modifies a document where there was no value for the owner_id field (%exists) previous to the write operation (%%prev). An example of this kind of write operation is an insert of a new document.

Modify the validation rule to the following and click Save:

"%%user.id"

The new rule requires owner_id to equal the id of the user logged in to the ToDo app (%%user.id). MongoDB Stitch prevents write operations that fail this rule.

For more information on validation rules, see MongoDB Service Validation.

Allow All Other Fields

By default, the Allow All Other Fields flag under the owner_id field is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable Allow All Other Fields to control the shape of the documents. For more information, see MongoDB Service Rules.

Filters

Click on the Filters tab within the todo.items view.

By default, the collection has the following filter rule:

When Match Expression
{ "%%true": true } { "owner_id": "%%user.id" }

This filter indicates that when %%true equals true (i.e. always), apply the following filter { "owner_id": "%%user.id" } to the read and write operations. This filter is in addition to the query predicates for read and write operations.

For more information on filters, see MongoDB Service Filters.

C. Set Up Authentication

Estimated Time to Complete: ~10 minutes per service

1

Add authentication information in MongoDB Stitch.

In the Authentication 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/v1.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 Authentication section of the MongoDB Stitch Admin Console.

B. Configure Stitch for Facebook Authentication:

  1. Click Authentication in the left side navigation in the MongoDB Stitch console.

    The Authentication page displays the Authentication Providers information.

  2. For Facebook, click the Edit button.

  3. In the Edit Provider dialog,

    • Switch the Facebook toggle to enabled.
    • Enter your new Facebook App ID in the Client ID field and Facebook App Secret in Client Secret field.
  4. 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 app.

    • 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 application.

    • For Authorized JavaScript origins, enter the following:

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

      https://stitch.mongodb.com/api/client/v1.0/auth/callback
      
  8. Click Create.

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

B. Configure Stitch Admin Console for Google Authentication:

  1. Click Authentication in the left side navigation in the MongoDB Stitch console.

    The Authentication page displays the Authentication Providers information.

  2. For Google, click the Edit button.

  3. In the Edit Provider dialog,

    • Switch the Google toggle to enabled.
    • Enter your new Client ID and Client Secret from the google Web App client credentials.
  4. Click Save.

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

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

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.

The MainActivity.java file contains logic that instantiates a _client connection to your MongoDB Stitch app (line 23) as well as instantiates a MongoClient that provides access to the MongoDB service named mongodb-atlas in you MongoDB Stitch app.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private static final String TAG = "TodoApp";
private static final long REFRESH_INTERVAL_MILLIS = 1000;
private static final int RC_SIGN_IN = 421;

private CallbackManager _callbackManager;
private GoogleApiClient _googleApiClient;
private StitchClient _client;
private MongoClient _mongoClient;

private TodoListAdapter _itemAdapter;
private Handler _handler;
private Runnable _refresher;

private boolean _fbInitOnce;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

    _client = StitchClient.fromProperties(this);
    _client.addAuthListener(new MyAuthListener(this));
    _mongoClient = new MongoClient(_client, "mongodb-atlas");
    initLogin();
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.