ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

Accessing MongoDB from Android apps.

Updated on June 25, 2013

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.

Comments

    0 of 8192 characters used
    Post Comment

    • AlexK2009 profile image
      Author

      AlexK2009 5 years ago from Edinburgh, Scotland

      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

    • profile image

      ran 5 years ago

      Hi, can u please upload the code src?

      thanks a lot for a very good written article

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)