top of page

CONNECT ANDROID APP WITH MONGODB USING REALM

Updated: Jun 12, 2023

You are developing an app now you need to store a user specific data on a cloud server what you will do? you will use firebase storing and processing users data now what if someone told you that hey I have data in MongoDB database and now I need to use that data in my android app. In this case you will need to connect the android app with MongoDB database and today we are going to solve this problem using the realm SDK provided by MongoDB for developing mobile app with it.



WHAT IS REALM?

Realm is service provided by MongoDB to connect mobile apps with database. MongoDB Realm has open-source SDKs available for most popular languages, frameworks, and platforms. Each SDK is language-idiomatic and includes:

  • The core database APIs for creating and working with on-device databases.

  • The APIs you need for connecting to the Realm backend so you can make use of server-side features like Sync, Authentication, Functions, Triggers, and more.


HOW TO USE REALM?

In order to use realm first we need to create a realm app in MongoDB UI only project owners can create realm app so make sure you signed in as a project owner.


Navigate to realm tab in MongoDB


Click on Build Your Own App tab save apply it


Provide name of your app and select the database cluster in which you have users data stored


Click Create Realm Application.


Now we have to define the security rules to access the cluster data


Navigate to rules tab


Select collection and then select the permission template as shown in the diagram

In the field name of user id block you can write the field name of value in which you're storing userId for the time being you can use userId as shown in the image


click on configure collections and now you can see the REVIEW DRAFT AND DEPLOY button at the top, click on this button to publish your changes


Now, Move to home page of Realm and copy App ID from the home page we will use it in the future


We are done with realm UI, we will implement it in our app in next section


IMPLEMENTING REALM IN ANDROID APP?

Open project level build.gradle file and do the following changes

  1. In buildscript.repositories add jcenter()

  2. In allprojects.repositories add mavenCentral()

  3. In buildscript.dependencies add classpath "io.realm:realm-gradle-plugin:10.9.0"

At the end your project level build.gradle file should look like this


Now open app level build.gradle file and add realm plugin at the top to your file

apply plugin: 'realm-android'



NOTE : If your project is using kotlin then you need to add kotlin plugin before the realm plugin apply plugin: 'kotlin-kapt'


Now sync your project and after successful sync you're ready to use MongoDB in your app


INITIALIZING REALM IN ANDROID STUDIO

Before using realm in our app we first need to initialize the realm.

Realm.init(this);

Write the above line in your MainActivity.java file inside onCreate method (you have to call this line only once in your app lifecycle you can call it anywhere in app before using the features of MongoDB)


After initialization the realm we have to initialize the mongo database and collections.

but in order to initialize the database and collection we need the reference of MongoDB user and for creating the MongoDB user we will use MongoDB anonymous authentication so let's set activate it in MongoDB.


Go to MongoDB realm UI and navigate to Authentication and select Allow user to authenticate anonymously enable the provider and click on save as draft now click on review and deploy button


We can now logged in our app user as anonymous and hence we can initialize the MongoDB collection


Now, Open MainActivity.java file and declare the following variable

Realm uiThreadRealm;
MongoClient mongoClient;
MongoDatabase mongoDatabase;
MongoCollection<Document> mongoCollection;
User user;
App app;
String AppId = YOUR APP ID FROM REALM UI";

and inside onCreate method initialize the app as following

app = new App(new AppConfiguration.Builder(AppId).build());

After initializing the app authenticate user


if (app.currentUser() == null) {
    Toast.makeText(this, "user is null", Toast.LENGTH_SHORT).show();
    app.loginAsync(Credentials.anonymous(), new App.Callback<User>() {
        @Override
        public void onResult(App.Result<User> result) {
            if (result.isSuccess()) {
                Log.v("User", "Logged In Successfully");
                initializeMongoDB();
                Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_LONG).show();
            } else {
                Log.v("User", "Failed to Login");
                Toast.makeText(MainActivity.this, "Failed to login", Toast.LENGTH_SHORT).show();
            }
        }
    });
} else {
    Toast.makeText(this, "user is not null", Toast.LENGTH_SHORT).show();
    initializeMongoDB();
}

Implementation of initializeMongoDB() method

//implementation of initializeMongoDB() method 
private void initializeMongoDB() {
    user = app.currentUser();
    mongoClient = user.getMongoClient("mongodb-atlas");
    mongoDatabase = mongoClient.getDatabase("YOUR DATABASE NAME");
    mongoCollection = mongoDatabase.getCollection("YOUR COLLECTION NAME");
}

Now our all variables are initialized we will see the inserting document operation in next section


INSERTING DOCUMENT

For inserting a document create a new button and edit text in activity_main.xml file and give them id button and name respectively now in the onClick listner of button paste the following code

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user == null)
                    user = app.currentUser();

                Document document = new Document().append("Name", b.name.getText().toString()).append("myid", "1234").append("userId", user.getId());
                mongoCollection.insertOne(document).getAsync(result -> {
                    if (result.isSuccess()) {
//                        BsonObjectId insertedId = result.get().getInsertedId().asObjectId();
//                        Log.v("adding", "result");
                        Toast.makeText(MainActivity.this, "Inserted successfully", Toast.LENGTH_LONG).show();
                    } else {
//                        Log.v("adding", "result failed" + result.getError().toString());
                        Toast.makeText(MainActivity.this, "Error " + result.getError(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        });

Please note that in document.append field you can put any value you want to insert in MongoDB but the .append("userId",user.getId()); field is always necessary because we had provided the userID as a authentication field while writing the rules for database access.


above code will create a new document in mongoDB atlas.


similarly you can do more operations like write, delete, update etc. using the same reference for more details visit this link.


IMPORTANT LINKS:



Codersarts is a top rated website for Android App Assignment Help, Project Help, Homework Help and Mentorship. Our dedicated team of Android assignment experts will help and guide you throughout your android app development journey.


bottom of page