Accessing MongoDB from Android apps.

Most devices now need to connect to a network, and phones are becoming the popular instrument of choice for connecting to the Internet. Equally, NoSql databases are becoming increasingly popular in the Enterprise. It therefore seemed logical to try to connect an Android phone app to an instance of MongoDB, a popular, document based NoSql database.

The Android operating system does not, by default, allow connection to the Internet, and, if connection is enabled, also prevents, by default, a blocking connection to the internet. The MongoDB drivers currently available do not support Android. It was necessary therefore to create an intermediary, in this case a web application, to handle accessing the database and returning the result to the caller. This solution is better than direct connection because it provides for multiple client types, server side data cleaning and additional security. For this proof of concept exercise, with test data invented purely for the project, security was not an issue, but would have to be addressed in any serious application.

The project fell into the following phases:

  • Simplifying access to the Database

  • Implementing the Android interface

  • Ensuring the device could contact the intervening web application

    Each phase involved behaviour driven development: The desired behaviour was known and unit tests ensured the correct behaviour.

The code shown here was developed in Eclipse using the Android Plugin, SDK and emulator and is still under development, but this note covers the main problems encountered so far. Basic knowledge of MongoDB and Android is assumed.

Use the code at your own risk. It comes with no guarantee whatsoever.

the MongoDB API

Developing for MongoDB gave the impression of requiring too many low level operations and a higher level API was needed to provide CRUD (create, read update, delete) functionality and should hide low level details from the client developer.

The database was provisioned from a BufferedReader with the contract that the first non empty line in the reader defined the schema. For test purposes the buffered reader was constructed from a text file. The data was converted into a List and each item in the List was then inserted into a Collection.

Typical code for provisioning the collection would, assuming a connection to the database and creation of the DBCollection be something like

BufferedReader reader = MongoUtilities.getBufferedReader(path_to_datafile);
List<DBObject> theList = MongoUtilities.readData(reader,delimiter);
testCollection.insert(theList); 

The provisioned Database can be accessed easily.


String expression = "joh?n"; 
String field = "firstname";      
DBCursor testCursor = MongoUtilities.searchCollection(testCollection,expression,field);

where expression is a Java Regular expression.

The results in the cursor can be converted to a string for transmission

String result = MongoUtilities.cursorToString(testCursor,"\n");

And of course the Collection can be updated

A typical update sequence to change all occurrences of first name “john” to “Frank” would be

String operator = "$set";
BasicDBObject criterion =   new BasicDBObject("firstname", "john");
BasicDBObject replacement = new BasicDBObject("firstname", "Frank");
MongoUtilities.updateCollection(testCollection, operator, criterion, replacement);

The Android Implementation

For this exercise only a single Android activity was used and the search was extremely inflexible. Both these failings will be addressed in future versions. Currently the user can enter a first name and see all records that have that value of the first name field. If the user fails to enter a search term the web application asks them to enter a term.

In order that the device can contact the server the following line has to be placed at the end of the Android Manifest.

<uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>

By default Android does not allow networking in the main UI thread. This is because the resulting blocking call to could result in a slow server response. While this behaviour can be overridden the recommended way to handle this situation is to extend the Android AsyncTask class and override the doInBackground(......)method. A skeleton implementation looks like

     public class DownloadWebpageText extends AsyncTask<String,String,String> 
{
    @Override
        protected String doInBackground(String... urls) {
            try {
                return downloadUrl(urls[0],500);   
            } catch (IOException e) {
                return "cannot retrieve web page: " + urls[0] + " URL may be invalid.";
            }
...
        }

The first class parameter is the URL, the second is the progress report and the third is the result. Here they are all of type String and only the first 500 characters are returned.

AsyncTask runs a task in the background thus improving responsiveness.

In the method that responds to search initiation all we need only to create the connector

DownloadWebpageText connector = new DownloadWebpageText();

create the url (hint: use your host name not localhost)

String theUrl=...;

if(!(theTerm==null && theTerm.length()==0)) { theUrl += "?firstname=" + theTerm; }

Where theTerm is the term entered by the user

TextView searchTerm = (TextView) findViewById(R.id.search_term);

And then call the execute method and retrieve the result.

AsyncTask<String, String, String> connectTask = connector.execute(theUrl);

String result = connectTask.get(); // retrieve the result of the query.

And finally put the result into the search_results field

TextView searchResults = (TextView) findViewById(R.id.search_results);

searchResults.setText( result);

The Web Application

The web application was a servlet. On the server side the code was straightforward,but one must be careful not to empty the database when connecting, hence the last parameter in getDBandCollection.

String query = request.getParameter("firstname");
if(query!=null && !query.isEmpty())
{
DBCollection testCollection = MongoUtilities.getDBandCollection(hostname, dbname, portnumber, collectionname, recreateDatabase=false);
DBCursor theCursor = MongoUtilities.searchCollection(testCollection, query, "firstname");
String result = MongoUtilities.cursorToString(theCursor,"\n");
out.println(result);
}
else
{
out.println("Please enter a search term. Thank you");
}

Recapitulation

This note outlines a first pass at accessing a MongoDB database from an Android device. Work needs to be done to complete the code, but the goal of accessing MongoDB from Android was achieved.

The original aim, direct connection, was abandoned after finding that Mongo DB does not at this time provide an Android Driver.

Mongo programming, as described on their site, requires a lot of low level detail which was hidden by an API developed for this project. This API is still under development.

Android does not permit networking in the main UI thread, because of the risk of a blocking call. This was overcome in the recommended fashion by extending the Android AsyncTask class. In addition the Android manifest had to be edited to allow the App to use the Internet.

Android's internet restrictions and security considerations meant an intermediary had to be created between the application and the database. Here this was a servlet, the code for which was straightforward.

More by this Author


Comments 2 comments

AlexK2009 profile image

AlexK2009 3 years ago from Edinburgh, Scotland Author

Thanks Ran. I will try to find time to put the source somewhere but first I have to resurrect the project: I have been involved with Big Data recently, not Android


ran 3 years ago

Hi, can u please upload the code src?

thanks a lot for a very good written article

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working