a good time to be a software development engineer


In this tutorial, i introduce MongoDB and MongoLab,  a hosting service for MongoDB databases. I guide you on how to make your first Android MongoLab hosted application.

A MongoDB database is made up of collections and documents (structured). 

Collections: You can think about a collection as an SQL table. Collections group related documents together.

Documents (structured): You can think of documents as rows in an SQL table. Documents contain detailed information about a given object. e.g. You can have a document containing patient medical information. You can read more about mongodb from here.

Screenshot_2014-05-17-23-56-27

Before you begin the tutorial, do tasks 1 – 4

1. Register on www.mongolab.com

2. Create a database named code101 (Choose the free sandbox 512MB)

3. Create a collection named docs101

4. Get your API key.  NB: You can find it by clicking on your user name in the top right corner and scrolling to the bottom of the page

The code is available for download from github.

 

Figure 1: Final Product

Create a new android application. NB: We are using REST and not the java driver.

The MyContact defines the data fields that are stored.

package com.wordpress.michaelkyazze.codeperspective101;

public class MyContact {

public String first_name;
public String last_name;
public String phone;
public String email;

}

 

The QueryBuilder class contains the code that builds the MongoHQ webservice. I have commented the code for your convenience

package com.wordpress.michaelkyazze.codeperspective101.MongoHQ;

import com.wordpress.michaelkyazze.codeperspective101.MyContact;

public class QueryBuilder {

 /**
 * Specify your database name here
 * @return
 */
 public String getDatabaseName() {
 return "code101";
 }

 /**
 * Specify your MongoLab API here
 * @return
 */
 public String getApiKey() {
 return ".....PUT YOUR API KEY HERE.......";
 }

 /**
 * This constructs the URL that allows you to manage your database,
 * collections and documents
 * @return
 */
 public String getBaseUrl()
 {
 return "https://api.mongolab.com/api/1/databases/"+getDatabaseName()+"/collections/";
 }

 /**
 * Completes the formating of your URL and adds your API key at the end
 * @return
 */
 public String docApiKeyUrl()
 {
 return "?apiKey="+getApiKey();
 }

 /**
 * Returns the docs101 collection
 * @return
 */
 public String documentRequest()
 {
 return "docs101";
 }

 /**
 * Builds a complete URL using the methods specified above
 * @return
 */
 public String buildContactsSaveURL()
 {
 return getBaseUrl()+documentRequest()+docApiKeyUrl();
 }

 /**
 * Formats the contact details for MongoHQ Posting
 * @param contact: Details of the person
 * @return
 */
 public String createContact(MyContact contact)
 {
 return String
 .format("{\"document\" : {\"first_name\": \"%s\", "
 + "\"last_name\": \"%s\", \"email\": \"%s\", "
 + "\"phone\": \"%s\"}, \"safe\" : true}",
 contact.first_name, contact.last_name, contact.email, contact.phone);
 }

}</pre>
<pre>

 

Android MainActivity Class Code:

package com.wordpress.michaelkyazze.codeperspective101;

import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.wordpress.michaelkyazze.codeperspective101.MongoHQ.SaveAsyncTask;

public class MainActivity extends Activity {
 EditText editText_last_name;
 EditText editText_phone;
 EditText editText_email;
 EditText editText_fname;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 editText_fname = (EditText) findViewById(R.id.editText_fname);
 editText_last_name = (EditText) findViewById(R.id.editText_last_name);
 editText_email = (EditText) findViewById(R.id.editText_email);
 editText_phone = (EditText) findViewById(R.id.editText_phone);

 }

 public void saveContact(View v) throws UnknownHostException {

 MyContact contact = new MyContact();
 contact.first_name = editText_fname.getText().toString();
 contact.last_name = editText_last_name.getText().toString();
 contact.email = editText_email.getText().toString();
 contact.phone = editText_phone.getText().toString();

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

 }

}

 

The contact is now saved in your MongoLab Database. To view it, simply browse to your docs101 collection at Mongolab.com. The Next part of the tutorial will cover Reading,Updating and Deleting

“Happy Coding :)”

 

Comments on: "Android, MongoDB, MongoLab Hosted Sample App Part One" (37)

  1. Richard said:

    Nice Kyazze

  2. nice article. can you point me to the next part of the tutorial if available regarding Reading,Updating and Deleting. Thanks

  3. Can I please ask whether the way that you have linked the two with the Rest API makes your android app secure?

    On mongolab website, they said the following:

    ‘Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.’

    • The API KEY gives your app users direct access to your database. If someone is to reverse engineer your android app, they will gain access to your API KEY and can wreck havoc. You need to build an authentication layer that directly accesses your REST API. The client devices can then gain access through a custom authentication layer.

      • Thanks! I’m going to use app engine to connect to my android app and to my mongolab so that should be secure as I need to authenticate from my android app to google app engine then app engine will communicate with mongolab using the api key.

  4. Where is the SaveAsyncTask class.
    For me the contacts are not inserting into the database
    kindly explain which part of the code is insert code
    thank you in advance

  5. Hi sarika, ensure that you supply your API key in the QueryBuilder class, also check the error logs in your IDE. you can then share the error for assistance.

  6. very useful tuto
    thanks a lot

  7. Saved my weekend! Is almost all that I need. Thanks a lot. =D

  8. Akshant poonia said:

    build failed because for database name and api key, cant find a symbol variable

  9. Kindly attach a screenshot of your logcat. Also make sure that your API key and database name are set

  10. I am not able to retrieve data from the database, can i know what could be the possible errors ?

  11. How to run different queries in this code to get Required data from database?

  12. build failed because 13 errors like “package org.apache.http does not exist”. I think it because of some missing dependencies in my build gradle file.
    can u please share the build gradle file of this app?

  13. Dhawan Gupta said:

    Hi
    Since, HttpClient, HttpPost and HttpResponse are deprecated, can you show how to create new entry using HttpURLConnection and OutputStreamWriter?
    Similar to what you did in GetUserAsyncTask and UpdateUserAsyncTask.

  14. Hello really interesting post. I wonder if its possible to use MongoDB Java Driver instead of Rest API and which changes i would need to make

    Thanks

  15. Really easy to understand what you’ve done!
    I’ve downloaded your code from GitHub but I cannot manage to save data to the DB. There are no errors on the Log.
    I’ve also replaced my ApiKey on getApiKey() method.

    Do you know what’s probably happening?

  16. Okey, sorry.
    I’ve managed to save the data. If someone is having the same problem as me, make sure that you have data access enabled.

    To do it, click on your user name in the top right corner and scroll to the bottom of the page. Clic on button “Enable Data API Access”

  17. **************Hi, I want to do the same , but have to store android sensor data. The above is working fine for storing name,email and al but not working in case of sensors.**********

    Kindly help me !! Its eating my time..!!!

  18. I want to know is there any code to retrieve data

  19. Notsomelancholyanymore said:

    Can someone tell me what file should be created for the mongohq??

  20. hello, the labeling on the save button is incorrect, I used mongolab, now known as mlab (https://mlab.com/). However, you can also use mongohq, now known as compose. Visit mlab and create an account, you will then get an API key. I advise that you don’t directly embed your API key into the app, rather create a REST service that interfaces with your app. This way, you can easily change your API keys or database providers without requiring your users to update the app.

  21. Notsomelancholyanymore said:

    hi, the SaveAsyncTask used in the savecontact function is not working. There is an error saying that the package doesnot exist. I also removed the folder and used it as it is still it is not working.

Leave a comment