Nimblechapps Blog

This is the section where we get a chance to rant about latest happenings in the tech world. Keen to know our thoughts? Refer our blogs

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.

[huge_it_slider id=”2″]

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.

[huge_it_slider id=”3 “]

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.

[huge_it_slider id=”4 “]

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.

[pastacode lang=”java” manual=”public%20class%20MyContact%20%7B%0Apublic%20String%20first_name%3B%0Apublic%20String%20last_name%3B%0Apublic%20String%20phone_nubmer%3B%0A%0Apublic%20String%20getFirst_name()%20%7B%0Areturn%20first_name%3B%0A%7D%0Apublic%20void%20setFirst_name(String%20first_name)%20%7B%0Athis.first_name%20%3D%20first_name%3B%0A%7D%0Apublic%20String%20getLast_name()%20%7B%0Areturn%20last_name%3B%0A%7D%0Apublic%20void%20setLast_name(String%20last_name)%20%7B%0Athis.last_name%20%3D%20last_name%3B%0A%7D%0Apublic%20String%20getPhone_nubmer()%20%7B%0Areturn%20phone_nubmer%3B%0A%7D%0Apublic%20void%20setPhone_number(String%20phone_nubmer)%20%7B%0Athis.phone_nubmer%20%3D%20phone_nubmer%3B%0A%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

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.

[pastacode lang=”java” manual=”public%20class%20SupportData%20%7B%0Apublic%20String%20getDatabaseName()%20%7B%0Areturn%20%22navyadb%22%3B%0A%7D%0Apublic%20String%20getApiKey()%20%7B%0Areturn%20%22UMDZcCfjpT_J7dmulkJcCXQC8-EncueV%22%3B%0A%7D%0Apublic%20String%20getBaseUrl()%0A%7B%0Areturn%20%22https%3A%2F%2Fapi.mlab.com%2Fapi%2F1%2Fdatabases%2F%22%2BgetDatabaseName()%2B%22%2Fcollections%2F%22%3B%0A%7D%0Apublic%20String%20apiKeyUrl()%0A%7B%0Areturn%20%22%3FapiKey%3D%22%2BgetApiKey()%3B%0A%7D%0Apublic%20String%20collectionName()%0A%7B%0Areturn%20%22Contacts%22%3B%0A%7D%0Apublic%20String%20buildContactsSaveURL()%0A%7B%0Areturn%20getBaseUrl()%2BcollectionName()%2BapiKeyUrl()%3B%0A%7D%0Apublic%20String%20buildContactsFetchURL()%0A%7B%0Areturn%20getBaseUrl()%2BcollectionName()%2BapiKeyUrl()%3B%0A%7D%0Apublic%20String%20createContact(MyContact%20contact)%20%7B%0Areturn%20String.format(%22%7B%5C%22first_name%5C%22%3A%20%5C%22%25s%5C%22%2C%20%22%2B%20%22%5C%22last_name%5C%22%3A%20%5C%22%25s%5C%22%2C%20%22%20%2B%20%22%5C%22phone%5C%22%3A%20%5C%22%25s%5C%22%7D%22%2C%20contact.getFirst_name()%2C%20contact.getLast_name()%2C%20contact.getPhone_nubmer())%3B%0A%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

Here is my XML layout Design:

[pastacode lang=”java” manual=”%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%0A%3CRelativeLayout%20xmlns%3Aandroid%3D%22http%3A%2F%2Fschemas.android.com%2Fapk%2Fres%2Fandroid%22%0Axmlns%3Atools%3D%22http%3A%2F%2Fschemas.android.com%2Ftools%22%0Aandroid%3Alayout_width%3D%22match_parent%22%0Aandroid%3Alayout_height%3D%22match_parent%22%0Aandroid%3ApaddingBottom%3D%22%40dimen%2Factivity_vertical_margin%22%0Aandroid%3ApaddingLeft%3D%22%40dimen%2Factivity_horizontal_margin%22%0Aandroid%3ApaddingRight%3D%22%40dimen%2Factivity_horizontal_margin%22%0Aandroid%3ApaddingTop%3D%22%40dimen%2Factivity_vertical_margin%22%0Atools%3Acontext%3D%22.MainActivity%22%20%3E%0A%0A%3CEditText%0Aandroid%3Aid%3D%22%40%2Bid%2FfirstName%22%0Aandroid%3Alayout_width%3D%22wrap_content%22%0Aandroid%3Alayout_height%3D%22wrap_content%22%0Aandroid%3Ahint%3D%22First%20Name%22%0Aandroid%3Aems%3D%2210%22%0Aandroid%3Alayout_centerHorizontal%3D%22true%22%0Aandroid%3Alayout_alignParentTop%3D%22true%22%0Aandroid%3Alayout_marginTop%3D%2270dp%22%2F%3E%0A%0A%3CEditText%0Aandroid%3Aid%3D%22%40%2Bid%2FlastName%22%0Aandroid%3Alayout_width%3D%22wrap_content%22%0Aandroid%3Alayout_height%3D%22wrap_content%22%0Aandroid%3Ahint%3D%22Last%20Name%22%0Aandroid%3Aems%3D%2210%22%0Aandroid%3Alayout_centerHorizontal%3D%22true%22%0Aandroid%3Alayout_alignTop%3D%22%40%2Bid%2FfirstName%22%0Aandroid%3Alayout_marginTop%3D%2260dp%22%2F%3E%0A%0A%3CEditText%0Aandroid%3Aid%3D%22%40%2Bid%2FphoneNumber%22%0Aandroid%3Alayout_width%3D%22wrap_content%22%0Aandroid%3Alayout_height%3D%22wrap_content%22%0Aandroid%3Ahint%3D%22Phone%20Number%22%0Aandroid%3Aems%3D%2210%22%0Aandroid%3Alayout_centerHorizontal%3D%22true%22%0Aandroid%3Alayout_alignTop%3D%22%40%2Bid%2FlastName%22%0Aandroid%3Alayout_marginTop%3D%2260dp%22%2F%3E%0A%0A%3CButton%0Aandroid%3Aid%3D%22%40%2Bid%2Fsave%22%0Aandroid%3Alayout_width%3D%22wrap_content%22%0Aandroid%3Alayout_height%3D%22wrap_content%22%0Aandroid%3Alayout_alignTop%3D%22%40%2Bid%2FphoneNumber%22%0Aandroid%3Alayout_centerHorizontal%3D%22true%22%0Aandroid%3Alayout_marginTop%3D%22100dp%22%0Aandroid%3Aems%3D%228%22%0Aandroid%3AonClick%3D%22save%22%0Aandroid%3Atext%3D%22Save%20to%20DB%22%0Aandroid%3AtextAllCaps%3D%22false%22%20%2F%3E%0A%0A%3CButton%0Aandroid%3Aid%3D%22%40%2Bid%2Ffetch%22%0Aandroid%3Alayout_width%3D%22wrap_content%22%0Aandroid%3Alayout_height%3D%22wrap_content%22%0Aandroid%3Alayout_alignTop%3D%22%40%2Bid%2Fsave%22%0Aandroid%3Alayout_centerHorizontal%3D%22true%22%0Aandroid%3Alayout_marginTop%3D%2270dp%22%0Aandroid%3Aems%3D%228%22%0Aandroid%3AonClick%3D%22fetch%22%0Aandroid%3Atext%3D%22Fetch%20from%20DB%22%0Aandroid%3AtextAllCaps%3D%22false%22%20%2F%3E%0A%0A%3CButton%0Aandroid%3Aid%3D%22%40%2Bid%2Freset%22%0Aandroid%3Alayout_width%3D%22wrap_content%22%0Aandroid%3Alayout_height%3D%22wrap_content%22%0Aandroid%3Alayout_alignParentRight%3D%22true%22%0Aandroid%3Alayout_alignParentTop%3D%22true%22%0Aandroid%3AonClick%3D%22reset%22%0Aandroid%3Atext%3D%22Reset%22%0Aandroid%3AtextAllCaps%3D%22false%22%20%2F%3E%0A%3C%2FRelativeLayout%3E” message=”” highlight=”” provider=”manual”/]

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.

[pastacode lang=”java” manual=”public%20void%20save(View%20v)%20%7B%0AMyContact%20contact%20%3D%20new%20MyContact()%3B%0A%0Acontact.setFirst_name(editText_fname.getText().toString())%3B%0Acontact.setLast_name(editText_lname.getText().toString())%3B%0Acontact.setPhone_number(editText_phonenumber.getText().toString())%3B%0A%0AMongoLabSaveContact%20tsk%20%3D%20new%20MongoLabSaveContact()%3B%0Atsk.execute(contact)%3B%0A%0AToast.makeText(this%2C%20%22Saved%20to%20MongoDB!!%22%2C%20Toast.LENGTH_SHORT).show()%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”java” manual=”final%20class%20MongoLabSaveContact%20extends%20AsyncTask%3CObject%2C%20Void%2C%20Boolean%3E%20%7B%0A%40Override%0Aprotected%20Boolean%20doInBackground(Object…%20params)%20%7B%0AMyContact%20contact%20%3D%20(MyContact)%20params%5B0%5D%3B%0ALog.d(%22contact%22%2C%20%22%22%2Bcontact)%3B%0A%0Atry%20%7B%0ASupportData%20sd%20%3D%20new%20SupportData()%3B%0AURL%20url%20%3D%20new%20URL(sd.buildContactsSaveURL())%3B%0A%0AHttpURLConnection%20connection%20%3D%20(HttpURLConnection)%20url%0A.openConnection()%3B%0Aconnection.setRequestMethod(%22PUT%22)%3B%0Aconnection.setDoOutput(true)%3B%0Aconnection.setRequestProperty(%22Content-Type%22%2C%0A%22application%2Fjson%22)%3B%0Aconnection.setRequestProperty(%22Accept%22%2C%20%22application%2Fjson%22)%3B%0A%0AOutputStreamWriter%20osw%20%3D%20new%20OutputStreamWriter(%0Aconnection.getOutputStream())%3B%0A%0Aosw.write(sd.createContact(contact))%3B%0Aosw.flush()%3B%0Aosw.close()%3B%0A%0Aif(connection.getResponseCode()%20%3C205)%0A%7B%0Areturn%20true%3B%0A%7D%0Aelse%0A%7B%0Areturn%20false%3B%0A%7D%0A%0A%7D%20catch%20(Exception%20e)%20%7B%0Ae.getMessage()%3B%0ALog.d(%22Got%20error%22%2C%20e.getMessage())%3B%0Areturn%20false%3B%0A%7D%0A%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

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.

[pastacode lang=”java” manual=”public%20void%20fetch(View%20v)%7B%0AGetContactsAsyncTask%20task%20%3D%20new%20GetContactsAsyncTask()%3B%0Atry%20%7B%0AreturnValues%20%3D%20task.execute().get()%3B%0AMyContact%20FetchedData%20%3D%20(MyContact)%20returnValues.toArray()%5B0%5D%3B%0A%0AeditText_fname.setText(FetchedData.getFirst_name())%3B%0AeditText_lname.setText(FetchedData.getLast_name())%3B%0AeditText_phonenumber.setText(FetchedData.getPhone_nubmer())%3B%0A%0AToast.makeText(this%2C%20%22Fetched%20from%20MongoDB!!%22%2C%20Toast.LENGTH_SHORT).show()%3B%0A%0A%7D%20catch%20(InterruptedException%20e)%20%7B%0Ae.printStackTrace()%3B%0A%7D%20catch%20(ExecutionException%20e)%20%7B%0Ae.printStackTrace()%3B%0A%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”java” manual=”public%20class%20GetContactsAsyncTask%20extends%20AsyncTask%3CMyContact%2C%20Void%2C%20ArrayList%3CMyContact%3E%3E%20%7B%0Astatic%20String%20server_output%20%3D%20null%3B%0Astatic%20String%20temp_output%20%3D%20null%3B%0A%0A%40Override%0Aprotected%20ArrayList%3CMyContact%3E%20doInBackground(MyContact…%20arg0)%20%7B%0A%0AArrayList%3CMyContact%3E%20mycontacts%20%3D%20new%20ArrayList%3CMyContact%3E()%3B%0ATry%20%7B%0ASupportData%20sd%20%3D%20new%20SupportData()%3B%0AURL%20url%20%3D%20new%20URL(sd.buildContactsFetchURL())%3B%0AHttpURLConnection%20conn%20%3D%20(HttpURLConnection)%20url%0A.openConnection()%3B%0Aconn.setRequestMethod(%22GET%22)%3B%0Aconn.setRequestProperty(%22Accept%22%2C%20%22application%2Fjson%22)%3B%0A%0Aif%20(conn.getResponseCode()%20!%3D%20200)%20%7B%0Athrow%20new%20RuntimeException(%22Failed%20%3A%20HTTP%20error%20code%20%3A%20%22%0A%2B%20conn.getResponseCode())%3B%0A%7D%0A%0ABufferedReader%20br%20%3D%20new%20BufferedReader(new%20InputStreamReader(%0A(conn.getInputStream())))%3B%0A%0Awhile%20((temp_output%20%3D%20br.readLine())%20!%3D%20null)%20%7B%0Aserver_output%20%3D%20temp_output%3B%0A%7D%0A%0AString%20mongoarray%20%3D%20%22%7B%20DB_output%3A%20%22%2Bserver_output%2B%22%7D%22%3B%0AObject%20o%20%3D%20com.mongodb.util.JSON.parse(mongoarray)%3B%0A%0ADBObject%20dbObj%20%3D%20(DBObject)%20o%3B%0ABasicDBList%20contacts%20%3D%20(BasicDBList)%20dbObj.get(%22DB_output%22)%3B%0Afor%20(Object%20obj%20%3A%20contacts)%20%7B%0ADBObject%20userObj%20%3D%20(DBObject)%20obj%3B%0A%0AMyContact%20temp%20%3D%20new%20MyContact()%3B%0Atemp.setFirst_name(userObj.get(%22first_name%22).toString())%3B%0Atemp.setLast_name(userObj.get(%22last_name%22).toString())%3B%0Atemp.setPhone_number(userObj.get(%22phone%22).toString())%3B%0Amycontacts.add(temp)%3B%0A%0A%7D%0A%0A%7Dcatch%20(Exception%20e)%20%7B%0Ae.getMessage()%3B%0A%7D%0A%0Areturn%20mycontacts%3B%0A%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

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…