Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 18, 2018 10:48 pm

How to Use MongoDB Stitch in Android Apps

With MongoDB Atlas, all it takes is a few clicks in the browser to get your own MongoDB cluster up and running in the cloud. By using it, you can build Android and iOS apps that can serve millions of users efficiently. However, you'd still need a back-end server that can act as an intermediary between your users' devices and your cluster. You'd need it to enforce security policies, add a level of abstraction to your CRUD operations, schedule jobs, and for a lot of other such important tasks.

MongoDB Stitch is a powerful serverless platform that can meet all your back-end requirements. In addition to providing fine-grained access control to the data in your MongoDB Atlas cluster, it offers a JavaScript-based compute environment you can use to perform a wide variety of server-side operations. In this tutorial, I'm going to show you how to use the platform in an Android app.

Prerequisites

To follow along, you'll need:


1. Create a MongoDB Atlas Cluster

MongoDB Stitch is meant to be used with a MongoDB Atlas cluster. You're free to use a cluster you already have, but I suggest you create a new one for this tutorial.

Start by logging into your MongoDB Atlas account and pressing the Build a New Cluster button.

MongoDB Atlas home page

In the next screen, which asks you for configuration details about your new cluster, choose any cloud provider, a region that offers an M0 free tier cluster, and press the Create Cluster button.

Cluster creation wizard

After a few minutes, you will have a brand new free tier cluster named Cluster0.


2. Create a MongoDB Stitch Application

To associate a Stitch application with your cluster, click on the the Link Application link. In the page that opens next, press the Create New Application button.

You can now type in the name you want for your new Stitch application. After you do so, make sure that the right cluster is selected and press the Create button.

New Stitch app dialog

At this point, your Stitch application—with very generous free quotas—is ready.

Stitch app overview

The application has a unique ID you'll need while developing your Android app. You can see what it is by going to the Clients section and opening the Java (Android) tab.

Stitch app ID


3. Configure Users and Rules

By using MongoDB Stitch, you can safely write web and mobile front-end code to interact with your MongoDB Atlas cluster. This is possible because you won't have to include a connection string containing your database's server address, username and password in your code.

Authenticated end users of your Stitch application automatically gain access to your database. Using one or more rules, however, you can control precisely which documents and fields they can see or modify.

To authenticate your users, Stitch offers several authentication mechanisms, including anonymous authentication, email/password authentication, and authentication using popular federated identity providers. In this tutorial, we'll be using anonymous authentication. To set it up, go to the Users section and open the Providers tab.

List of authentication providers

Next, select the Allow users to log in anonymously option, enable it, and press the Save button.

Let's say we want to allow our anonymous users to work with only the documents they own. To create such a rule, go to the Rules section.

Because rules are applied to collections, press the Add Collection button to create a new collection now. In the form that appears, give a name to it and specify which database it must belong to. After you do so, select the Users can only read and write their own data rules template.

Add new collection page

On selecting the template, you'll be prompted to specify the name of the field in your document in which you'll be storing the user's auto-generated Stitch auth ID. Stitch will use this field while deciding whether a document belongs to a user or not. Say the name is user_id and submit the form.

In the page that opens next, you can now confirm that only the owners of the documents in your collection can perform read and write operations on them.

Collections permissions page


4. Prepare Android Project

To be able to use Stitch in your Android Studio project, you must add its official SDK as an implementation dependency in your app module's build.gradle file.

Additionally, you must mention your Stitch app's unique ID in your project. So go to the res/values/strings.xml file and add it as a <string> tag.


5. Establish a Connection

With an instance of the StitchAppClient class, you can easily make use of all the features the Stitch platform offers. To initialize initialize StitchAppClient, you must call the initializeDefaultAppClient() method and pass your Stitch app's ID to it. This needs to be done only once in your app, preferably as soon as it starts.

Once it's ready, you can call the getDefaultAppClient() method to get a reference to the client. The following code, which you can add to your activity's onCreate() method, shows you how:

Unless your user is logged into your Stitch app, you won't be able to perform any useful operations on your MongoDB Atlas cluster. Therefore, you must now log the user in by calling the loginWithCredential() method, which runs asynchronously and returns a Task object. Additionally, because you chose anonymous authentication as the authentication mechanism in Stitch's web console, make sure you pass an instance of the AnonymousCredential class to the method.

At this point, if you run the app, Stitch will automatically register you as a new user, and also log you into the app. What's more, if you go back to the Stitch web console and open the Users section, you'll be able to see that a new entry has been added to the list of users.

List of authenticated users


6. Insert Documents

After a successful authentication, you can go ahead and get an instance of the RemoteMongoClient class to start interacting with your MongoDB Atlas cluster. To do so, you can call the getServiceClient() method and specify that the name of the service you want is "mongodb-atlas". Here's how:

Remember that, thanks to the rule you created earlier in this tutorial, your user can only perform read and write operations on his or her own data. Furthermore, your user is limited to working only with the database and collection you mentioned in the Stitch web console.

To get a reference to the database, call the getDatabase() method and pass its name to it. Similarly, to get a reference to the collection, call the getCollection() method, which returns a RemoteMongoCollection object.

What you add to the collection is, of course, up to you. For the sake of an example, let's say we want to add documents containing timestamps of all the times at which the user opened the app.

To create a new BSON document, you must use the constructor of the Document class. Because Document objects are very similar to maps, you can use the [] operator to add key-value pairs to them.

The following code shows you how to create a new document and add a timestamp to it:

In addition to your data, all your documents must contain the user's Stitch auth ID. Without it, your insert operations will fail. To get the auth ID, you can directly use the id property of the implicit it object available inside the on-success listener.

You can now insert the document by calling the insertOne() method. (You can read about the insertOne() method and other write operations in the MongoDB documentation for the Java driver.) Because it runs asynchronously, you'll need another on-success listener to check if the insert operation succeeded.

If you run the app now and check Android Studio's Logcat panel, you should be able to see a log entry that looks like this:

Logcat panel displaying success message


7. Run Queries

By calling the find() method of your RemoteMongoCollection object, you can create a query. (You can learn more about find() and other query operations in the MongoDB Java driver documentation.)The method returns a RemoteFindIterable object, on which you can call more methods such as sort() and limit() to manage the results of the query. For instance, the following code creates a query to find the last five documents created by the user:

To actually run the query, you can call its into() method, which expects a list as an argument. As its name suggests, it loads the results of the query, which are nothing but Document objects, into the list you pass to it. It runs asynchronously, so you can start using the list only inside an on-success listener.

For now, to keep things simple, let's use a TextView widget to display the results of the query. So add the following code to your activity's layout XML file:

Back inside the on-success listener, you can now loop through the list and create a concatenated string containing all the timestamps. Optionally, you can pass the timestamps to the getRelativeDateTimeString() method of the DateUtils class to make them more readable. Once the string is ready, you can directly assign it to the TextView widget. Here's how:

If you run the app again, you should now see something like this on your device:

App displaying list of timestamps

Conclusion

MongoDB Stitch is a serverless platform you can use to create modern apps that can easily scale to handle large amounts of user data. In this tutorial, you learned how to use it to authenticate users of your Android apps anonymously and allow them to securely perform read and write operations on your MongoDB Atlas clusters.

To learn more about MongoDB Stitch, do refer to the official documentation.


Original Link:

Share this article:    Share on Facebook
No Article Link

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code