Using MongoDB For Storing and Retrieving Data For Android

Using MongoDB For Storing and Retrieving Data For Android

As a mobile app developer, we all know the importance of data and its storage. In Mobile applications, there is a need to store various kind of data like user information, location etc. MongoDB is one among those databases used for storing the desired data.

In this page, you will be going to hear more about MongoDB and using MongoDB for the Android applications.

MongoDB is an open-source, document-oriented database. It is classified as NoSQL database, which supports dynamic schemas. Here data is stored in JSON format. MongoDB is made up of collections and documents.

Collection


Group of MongoDB documents. It consists of one or more documents that can have a similar set of properties.

Document


Document is a set key-value pairs. As mentioned earlier, these documents have a dynamic schema.

Simply to say, you can think of MongoDB collection, document as an RDBMS table and row respectively.

PRO TIP My pockets are empty. How can I afford this? No, you don’t need to take out a single penny from your pocket. It comes with an absolutely free tag :P. Let’s start using such an attractive database in your Android applications.

Now we will be going to store and retrieve the data from our MongoDB. Here we are using MongoLab to access MongoDB. Let’s follow the below steps to complete our task.

1

Login to MongoLab and create a database and collections.

2

Get your API key.

3

Saving the data into the MongoDB collection.

4

Fetching the stored data from the MongoDB.

#1

Login to MongoLab and create databases and collections

We are using MongoLab to create MongoDB databases and collections. It is a cloud database service that hosts MongoDB databases.

Login to MongoLab https://mlab.com/login/. If you don’t have an account, create an account and login.

  • Upon successful login, you will be able to see the above screen. [1 of 5 Slides]
  • Currently, you do not have any database in your account. Under MongoDB Deployments section, Click on “Create new” to create one. Select SANDBOX plan type for free service. [2 of 5 Slides]
  • Upon successful creation, you can see your database details as shown in the below picture. Here I have created a database named “navyadb”. [3 of 5 Slides]
  • Click on the database name to create a collection. Here is the screen you will get now. [4 of 5 Sildes]
  • Click on ‘Add collection’ that is visible on the screen to create one collection. I have created a collection of “Contacts”. [5 of 5 Slides]

Congratulations!! You have created your own database and a collection in MongoDB.

#2

Get your API key

API key is the most important element you need for doing networking calls. Don’t panic, I will guide you to find out your key.

  • After logging into the MongoLab, on the rightmost top corner, you can see the user name as here. [1 of 2 Slides]
  • Click on the user name, you will be directed to another screen. Scroll down to see your API key. [2 of 2 Slides]

Copy that API key and save it somewhere. Later you need to use this in your project.

And on the same page you can see a field “Data API access”. If it’s value is disabled, click over the button “Enable Data API access” to enable the API access. Now we are ready to proceed further.

#3

Saving the data into the MongoDB collection

Till this point, we created a Database and a collection in it. Our next step is to save the data into the MongoDB. As already discussed, data will be stored in the form of Documents, which contains the JSON format data. There are two ways to save the data in the MongoDB. We will look at both.

One way is, saving the data directly in MongoLab.

There is an option to create a database in MongoLab, as similar to that of creating a collection and Database.

  • Click on the collection “Contacts”. You will be moved to collection details screen as given here. [1 of 3 Slides]
  • Now click on “Add document” and enter the data you want to store. [2 of 3 Slides]
  • Automatically ‘_id’ will be generated for your document to uniquely identify it. This is one of the simple process to store the data in MongoDB. [3 of 3 Slides]

The other way is doing Networking calls and save the data in the given URL. Okay… Let’s begin our coding part.

1

As a first step, create a new Project in Android Studio.

2

I would like to store First Name, Last Name and Phone number information in my MongoDB. Hence create a Class named MyContact as below that defines these data fields. It is a POJO class.

public class MyContact {
public String first_name;
public String last_name;
public String phone_nubmer;

public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getPhone_nubmer() {
return phone_nubmer;
}
public void setPhone_number(String phone_nubmer) {
this.phone_nubmer = phone_nubmer;
}
}

Now create another class SupportData, which can be used for having a database, collection names, your API key and the URL where you are going to save the data. Have the below code snippet.

public class SupportData {
public String getDatabaseName() {
return "navyadb";
}
public String getApiKey() {
return "UMDZcCfjpT_J7dmulkJcCXQC8-EncueV";
}
public String getBaseUrl()
{
return "https://api.mlab.com/api/1/databases/"+getDatabaseName()+"/collections/";
}
public String apiKeyUrl()
{
return "?apiKey="+getApiKey();
}
public String collectionName()
{
return "Contacts";
}
public String buildContactsSaveURL()
{
return getBaseUrl()+collectionName()+apiKeyUrl();
}
public String buildContactsFetchURL()
{
return getBaseUrl()+collectionName()+apiKeyUrl();
}
public String createContact(MyContact contact) {
return String.format("{\"first_name\": \"%s\", "+ "\"last_name\": \"%s\", " + "\"phone\": \"%s\"}", contact.getFirst_name(), contact.getLast_name(), contact.getPhone_nubmer());
}
}

Here is my XML layout Design:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
android:id="@+id/firstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="First Name"
android:ems="10"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_marginTop="70dp"/>

<EditText
android:id="@+id/lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Last Name"
android:ems="10"
android:layout_centerHorizontal="true"
android:layout_alignTop="@+id/firstName"
android:layout_marginTop="60dp"/>

<EditText
android:id="@+id/phoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:ems="10"
android:layout_centerHorizontal="true"
android:layout_alignTop="@+id/lastName"
android:layout_marginTop="60dp"/>

<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/phoneNumber"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:ems="8"
android:onClick="save"
android:text="Save to DB"
android:textAllCaps="false" />

<Button
android:id="@+id/fetch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/save"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:ems="8"
android:onClick="fetch"
android:text="Fetch from DB"
android:textAllCaps="false" />

<Button
android:id="@+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="reset"
android:text="Reset"
android:textAllCaps="false" />
</RelativeLayout>

The layout screen in the emulator looks like below.

layout-screen

From the above picture, you can observe that I have three edit texts for first name, last name and phone number. And also you can see one save button and one fetch button. My concern is, when I click save button, the user entered data in the edit text fields has to be stored into the MongoDB collection named “Contacts”, which I have created earlier.

Include the below code snippet for save button action in your MainActivity.class.

public void save(View v) {
MyContact contact = new MyContact();

contact.setFirst_name(editText_fname.getText().toString());
contact.setLast_name(editText_lname.getText().toString());
contact.setPhone_number(editText_phonenumber.getText().toString());

MongoLabSaveContact tsk = new MongoLabSaveContact();
tsk.execute(contact);

Toast.makeText(this, "Saved to MongoDB!!", Toast.LENGTH_SHORT).show();
}

And include AsyncTask method to perform Network call in a background thread. Have the below code into your MainActivity.class.

final class MongoLabSaveContact extends AsyncTask<Object, Void, Boolean> {
@Override
protected Boolean doInBackground(Object... params) {
MyContact contact = (MyContact) params[0];
Log.d("contact", ""+contact);

try {
SupportData sd = new SupportData();
URL url = new URL(sd.buildContactsSaveURL());

HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Accept", "application/json");

OutputStreamWriter osw = new OutputStreamWriter(
connection.getOutputStream());

osw.write(sd.createContact(contact));
osw.flush();
osw.close();

if(connection.getResponseCode() <205)
{
return true;
}
else
{
return false;
}

} catch (Exception e) {
e.getMessage();
Log.d("Got error", e.getMessage());
return false;
}
}
}
saving-you-data-into-MongoDB

#4

Fetching the stored data from the MongoDB

Be patient for few more minutes, we are almost near to our destination. We are able to save the data in the MongoDB using MongoLab. Now our final task is to fetch that data from MongoDB.

Include the below button action code for fetch in you MainActivity.class.

public void fetch(View v){
GetContactsAsyncTask task = new GetContactsAsyncTask();
try {
returnValues = task.execute().get();
MyContact FetchedData = (MyContact) returnValues.toArray()[0];

editText_fname.setText(FetchedData.getFirst_name());
editText_lname.setText(FetchedData.getLast_name());
editText_phonenumber.setText(FetchedData.getPhone_nubmer());

Toast.makeText(this, "Fetched from MongoDB!!", Toast.LENGTH_SHORT).show();

} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

Here I have written one more AsyncTask GetContactsAsyncTask for handling Network call that deals with fetching the data back to our application.

public class GetContactsAsyncTask extends AsyncTask<MyContact, Void, ArrayList<MyContact>> {
static String server_output = null;
static String temp_output = null;

@Override
protected ArrayList<MyContact> doInBackground(MyContact... arg0) {

ArrayList<MyContact> mycontacts = new ArrayList<MyContact>();
Try {
SupportData sd = new SupportData();
URL url = new URL(sd.buildContactsFetchURL());
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

while ((temp_output = br.readLine()) != null) {
server_output = temp_output;
}

String mongoarray = "{ DB_output: "+server_output+"}";
Object o = com.mongodb.util.JSON.parse(mongoarray);

DBObject dbObj = (DBObject) o;
BasicDBList contacts = (BasicDBList) dbObj.get("DB_output");
for (Object obj : contacts) {
DBObject userObj = (DBObject) obj;

MyContact temp = new MyContact();
temp.setFirst_name(userObj.get("first_name").toString());
temp.setLast_name(userObj.get("last_name").toString());
temp.setPhone_number(userObj.get("phone").toString());
mycontacts.add(temp);

}

}catch (Exception e) {
e.getMessage();
}

return mycontacts;
}
}

Now Run your project and check the output. The below given emulator output I got.

Project-Output

#5

Well done!! It’s time to congratulate yourself.

As promised, at the end of this page you will be able to use MongoDB in your Android applications to store and fetch the data.

Good Luck…

Navya Sri
Navya Sri is a developer who is passionate to learn new things. She loves coding, challenges and creativity. She got very good commanding on User Interface. Ready to share & gain knowledge.
  • Andrew Alizaga Guadamuz

    How about extracting from mlab?, I haven’t found much documentation of this kind, mostly I only found node.js tutorials, im trying to extract a single document through a manually coded variable, let’s say an user name, but I don’t get anything back, only now how to do it with the self-generated _id, I don’t know what would be the proper request in these cases, <- (with any other attribute declared by me and not self-generated). pd: thanks for your time

  • Always Ontime

    I think it is better to download json document from mlab and store data in sqllite database, and synchronize data when required, so that we don’t have to fetch data again and again…

  • Himanshu

    Here in this line: MyContact contact = (MyContact) params[0];
    The contacts gets inserted to every 0th index of json array. How can I insert the data in mlab as a new field rather than updating the current field?