a good time to be a software development engineer


This tutorial describes how to perform READ and UPDATE operations on a Mongolab hosted Mongodb database using a REST API. The first part of the tutorial can also be found at this blog

Lets dive in….

I have updated the structure of my contact record to the following.

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

MongoDB allows you to have a dynamic schema. Feel free to experinment with various schemas when you are done with this tutorial.

This code can be downloaded from github at this link

Screenshot_2014-09-22-23-40-58Screenshot_2014-09-22-23-44-26

Figure 1: List of contacts    Figure 2: Select and update a given record

 

Async Task to fetch contacts

package com.wordpress.michaelkyazze.codeperspective102.MongoLab;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.os.AsyncTask;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.wordpress.michaelkyazze.codeperspective102.MyContact;
/**
* Async Task to retrieve your stored contacts from mongolab
* @author KYAZZE MICHAEL
*
*/
public class GetContactsAsyncTask extends AsyncTask<MyContact, Void, ArrayList<MyContact>> {
static BasicDBObject user = null;
static String OriginalObject = "";
static String server_output = null;
static String temp_output = null;

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

ArrayList<MyContact> mycontacts = new ArrayList<MyContact>();
try
{

QueryBuilder qb = new QueryBuilder();
URL url = new URL(qb.buildContactsGetURL());
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;
}

// create a basic db list
String mongoarray = "{ artificial_basicdb_list: "+server_output+"}";
Object o = com.mongodb.util.JSON.parse(mongoarray);

DBObject dbObj = (DBObject) o;
BasicDBList contacts = (BasicDBList) dbObj.get("artificial_basicdb_list");

for (Object obj : contacts) {
DBObject userObj = (DBObject) obj;

MyContact temp = new MyContact();
temp.setDoc_id(userObj.get("_id").toString());
temp.setFirst_name(userObj.get("first_name").toString());
temp.setLast_name(userObj.get("last_name").toString());
temp.setEmail(userObj.get("email").toString());
temp.setPhone(userObj.get("phone").toString());
mycontacts.add(temp);

}

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

return mycontacts;
}
}

View contacts Activity

package com.wordpress.michaelkyazze.codeperspective102;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.wordpress.michaelkyazze.codeperspective101.R;
import com.wordpress.michaelkyazze.codeperspective102.MongoLab.GetContactsAsyncTask;

/**
* This activity retrieves the mongolab contacts and displays them in a listview.
* @author KYAZZE MICHAEL
*
*/
public class ViewContactsActivity extends ListActivity{
ArrayList<MyContact> returnValues = new ArrayList<MyContact>();
ArrayList<String> listItems = new ArrayList<String>();
String valueTOUpdate_id;
String valueTOUpdate_fname;
String valueTOUpdate_lname;
String valueTOUpdate_phone;
String valueTOUpdate_email;

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

//Get your cloud contacts
GetContactsAsyncTask task = new GetContactsAsyncTask();
try {
returnValues = task.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

for(MyContact x: returnValues){

listItems.add(x.getFirst_name());
}

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);

String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
selectedContact(selectedValue);

Bundle dataBundle = new Bundle();
dataBundle.putString("_id", valueTOUpdate_id);
dataBundle.putString("first_name", valueTOUpdate_fname);
dataBundle.putString("last_name", valueTOUpdate_lname);
dataBundle.putString("phone", valueTOUpdate_phone);
dataBundle.putString("email", valueTOUpdate_email);
Intent moreDetailsIntent = new Intent(this,UpdateContactsActivity.class);
moreDetailsIntent.putExtras(dataBundle);
startActivity(moreDetailsIntent);
}

/*
* Retrieves the full details of a selected contact.
* The details are then passed onto the Update Contacts Record.
*
* This is a quick way for demo purposes.
* You should consider storing this data in a database, shared preferences or text file
*/
public void selectedContact(String selectedValue){
for(MyContact x: returnValues){
if(selectedValue.contains(x.getFirst_name())){
valueTOUpdate_id = x.getDoc_id();
valueTOUpdate_fname = x.getFirst_name();
valueTOUpdate_lname = x.getLast_name();
valueTOUpdate_phone = x.getPhone();
valueTOUpdate_email = x.getEmail();
}
}

}
}

Happy Coding 🙂

Comments on: "Android, MongoDB, MongoLab Hosted Sample App Part Two" (28)

  1. Thanks for sharing this… Are you going to write a sample android app that sends and retrieves files using GRIDFS in mongoDB?

  2. I will write one. Keep visiting the blog 🙂

  3. Hi Michael, have you done the GRIDFS yet? Thanks.

  4. HI Michael,you tutorial roczzzzz… waiting for the next part:):) Thanks

  5. Ernő Simonyi said:

    Hi Michael, I ran into some trouble in the tutorial. I’m getting a “Could not find method javax.xml.bind.DatatypeConverter.parseBase64Binary, referenced from method com.mongodb.util.JSONCallback.objectDone” error message. Any idea what might be causing this? Thank you.

    • Can you paste the code block where the error occurs

      • Ernő Simonyi said:

        The error occurs in the GetContactsAsyncTask class at the: “Object o = com.mongodb.util.JSON.parse(mongoarray);” line. I solved it by making a JSONObject out of the “server_output” string, but found it strange that it didn’t work.

  6. I want to thank you for this 2nd tuto.
    and i need some help, i’am using this structure to create a user :
    public String createUser(UserEntity userEntity){
    JSONObject user = new JSONObject();
    user.accumulate(“fname”, userEntity.getFName());
    user.accumulate(“lname”, userEntity.getLName());
    return user.toString();
    }
    I want to modify it to update a user but I don’t know what does mean “$set” in your function :
    public String setContactData(MyContact contact) {
    return String.format(“{ \”$set\” : ”
    + “{\”first_name\” : \”%s\”, ”
    + “\”last_name\” : \”%s\”, ”
    + “\”email\” : \”%s\”, ”
    + “\”phone\” : \”%s\” }” + “}”,
    contact.getFirst_name(),
    contact.getLast_name(), contact.getEmail(),
    contact.getPhone());

  7. The $set operator replaces the value of a field with the specified value.In this case, it replaces %s with the contact object.

    Read more about the operator at:

    http://docs.mongodb.org/manual/reference/operator/update/set/

  8. Michael,
    You have written a comprehensive yet simple code, for beginners to understand and use it.
    I have used it successfully, but am facing a strange issue. The data is being saved (i.e. contact data, which I can see on my mongolab account), but the list is not being populated back (i.e. the “cloud address book” list displayed in the app finally). However, while the app is running (through system.out) I am able to see that it does retreive the data.
    I think, somehow the app is not able to get into the “for (Object obj : contacts) {” loop in the GetContactsAsyncTask.java file.
    Appreciate if you could help me out.
    PS: I have not changed anything in your code (from github) except the API key.
    cheers,
    Amit

    • Amit Wereyou able to resolve it.Am facing same problem?
      Michael your help would be appreciated

      D/GetNotice﹕ { artificial_basicdb_list: [ { “_id” : { “$oid” : “5634235ae4b03f7c515fbdfc”} , “document” : { “noticetitle” : “r” , “category” : “Jobs and Internships” , “description” : “xj” , “phone” : “0”} , “password” : “0”}
      , { “_id” : { “$oid” : “56343b01e4b03f7c51603678”} , “document” : { “noticetitle” : “bb” , “category” : “Jobs and Internships” , “description” : “sh” , “phone” : “0”} , “password” : “0”} ,
      { “_id” : { “$oid” : “56343c21e4b03f7c51603953”} , “document” : { “noticetitle” : “fjdj” , “category” : “Jobs and Internships” , “description” : “hjkll” , “phone” : “0”} , “password” : “0”} ,
      { “_id” : { “$oid” : “56343febe4b03f7c51606e5a”} , “document” : { “noticetitle” : “dd” , “category” : “Housing” , “description” : “ddcv” , “phone” : “0”} , “password” : “0”} ,
      { “_id” : { “$oid” : “56344129e4b03f7c51607135”} , “document” : { “noticetitle” : “dry” , “category” : “Housing” , “description” : “dk” , “phone” : “0”} , “password” : “0”} ]}
      10-30 23:18:45.372 25780-25871/com.iit.t1.u_board D/GetNotice﹕ Getinng list
      10-30 23:18:45.372 25780-25871/com.iit.t1.u_board D/Inside Loop﹕ Inside Loop

      For the below code .Its going inside the loop only once
      Not able to view the list.It is able to show the list. But the objects are retrieved from mongodb .No errors are thrown

      /**** for (Object obj : contacts) {
      Log.d(“Inside Loop”,”Inside Loop”);
      DBObject userObj = (DBObject) obj;
      UboardNotices temp = new UboardNotices();
      temp.setId(userObj.get(“_id”).toString());
      temp.setnoticeTitle(userObj.get(“noticetitle”).toString());
      temp.setDescription(userObj.get(“description”).toString());
      temp.setCategory(userObj.get(“category”).toString());
      Log.d(“GetNoticeBrd”,temp.toString());
      mycontacts.add(temp);
      }

    • Amit were you able to resolve it?
      I am facing the same problem. It is not displaying the list

      Mike your help is appreciated. No errors are thrown.

      It is able to retrieve the objects but not listing it in list. It goes inside the loop only once

      D/GetNotice﹕ { artificial_basicdb_list: [ { “_id” : { “$oid” : “5634235ae4b03f7c515fbdfc”} , “document” : { “noticetitle” : “r” , “category” : “Jobs and Internships” , “description” : “xj” , “phone” : “0”} , “password” : “0”}
      , { “_id” : { “$oid” : “56343b01e4b03f7c51603678”} , “document” : { “noticetitle” : “bb” , “category” : “Jobs and Internships” , “description” : “sh” , “phone” : “0”} , “password” : “0”} ,
      { “_id” : { “$oid” : “56343c21e4b03f7c51603953”} , “document” : { “noticetitle” : “fjdj” , “category” : “Jobs and Internships” , “description” : “hjkll” , “phone” : “0”} , “password” : “0”} ,
      { “_id” : { “$oid” : “56343febe4b03f7c51606e5a”} , “document” : { “noticetitle” : “dd” , “category” : “Housing” , “description” : “ddcv” , “phone” : “0”} , “password” : “0”} ,
      { “_id” : { “$oid” : “56344129e4b03f7c51607135”} , “document” : { “noticetitle” : “dry” , “category” : “Housing” , “description” : “dk” , “phone” : “0”} , “password” : “0”} ]}
      10-30 23:18:45.372 25780-25871/com.iit.t1.u_board D/GetNotice﹕ Getinng list
      10-30 23:18:45.372 25780-25871/com.iit.t1.u_board D/Inside Loop﹕ Inside Loop

      /**** for (Object obj : contacts) {
      Log.d(“Inside Loop”,”Inside Loop”);
      DBObject userObj = (DBObject) obj;
      UboardNotices temp = new UboardNotices();
      temp.setId(userObj.get(“_id”).toString());
      temp.setnoticeTitle(userObj.get(“noticetitle”).toString());
      temp.setDescription(userObj.get(“description”).toString());
      temp.setCategory(userObj.get(“category”).toString());
      Log.d(“GetNoticeBrd”,temp.toString());
      mycontacts.add(temp);
      }

      ***/

  9. Thanks Amit.
    Are you getting any errors? You can set a break-point at the point when the data is returned and you step over the code. Post any error messages that you may encounter
    Regards
    Michael

  10. Thanks, it helps me a lot. Could you post a tutorial to delete documents ?

  11. I am not able to retrieve data using the code, could you tell me what could be the possible errors ?

  12. Abhimanyu Srivastava said:

    listitems are not working . It’s not fetching the values. App is reading an exception

  13. I am not able to retrieve data using the code

  14. I am not able to retrieve data using the code . Plz help me with this

  15. Thanks for the nice examples.
    Can you show how can I query a specific document, and not having to get all of them? I want to quey by a specific field.

  16. it Good!! – 6/3/2016

  17. How to retrieve a specific document and display? please help!

  18. i can’t save data to mongolab.. i tried your code.. After clicking save button doesn’t show any message . what can i do for save data to mongolab.? Thanks advance

  19. Hello
    Thanks for your tutorial.
    How can I enter multiple documents to my database? Because with this code i only can introduce one document in my database.
    Please help me

  20. will u write a sample project for this so i can download?

Leave a comment