Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Working with Amazon SimpleDB in Android

4.58/5 (11 votes)
25 Jun 2014CPOL6 min read 25.4K   4  
This article contains the project and code for web service API of SimpleDB

Introduction

Amazon web service (AWS) provides the services to build the connected mobile applications. SimpleDB is web service provided by AWS for data storage in cloud. In this blog, e are going to see the connectivity of Android app with the AWS simpleDB. For more details about the SimpleDB, you can go to the following link- http://aws.amazon.com/simpledb/.

Background

SimpleDB Concept

SimpleDB is highly available data store. SimpleDB is non-relational data store with the simple web service API which make it easy for development process. SimpleDB provides the simple web service call for storing and retrieving the data stored in the Amazon SimpleDB.

For more details, you can go to the link here.

Being the non-relational database system SimpleDB uses different terminologies compared to the Normal Database System. The following table shows the terminologies used in Normal database system and Amazon SimpleDB.

Normal Database System Amazon Simple DB
Table Domain

Column

Attribute
Row Item

Using the Code

Now let's see step by step how we can work on the SimpleDB database from start to end. We will try to create a simple project to store the movie information at the SimpleDB and retrieve the information from the same.

In this project, we are going to create an application for the Movie database. This application will allow user to store the movie information in the SimpleDB and allow user to retrieve the movie information from the simpleDB.

For the above project requirement, we are going to design the SimpleDB domain ‘movie_info as follows:

Name Rating Description
Movie Name 1 3.5 Movie 1 Description
Movie Name 2 5.0 Movie 2 Description

Steps

For creating an Android app with the SimpleDB, you will need the following steps:

1. Create AWS account

For using the SimpleDB, you need to first create the AWS account. Use the following link for the login http://aws.amazon.com/ which is free.

  1. Go to link http://aws.amazon.com/simpledb/ for creating the AWS account.
  2. For more details about creating AWS account visit the link: http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/AboutAWSAccounts.html
2. Create Access Key Id and Secret Access Key for the SimpleDB
  1. Once the AWS account is created using the steps mentioned in step 1, you need to create the Access Key Id and Secret Access Key pair for the SimpleDB. Access Key Id and Secret Access Key will be used in our application for authentication the web service request for the SimpleDB database.
  2. Login to AWS account, click on the user name from the left top corner and select Security Credentials option from the list.
  3. On the next page, select the Users Options from the left side of the page.
  4. Click on the Create new Users button, enter the user name in the pop up.
  5. Once the user name is created, download and store the security credentials for the user.
  6. Downloaded credentials.csv file contains the user name, Access Key Id and Secret Access Key. Save credentials.csv file at the safe location.
  7. For performing the read, write operation on the SimpleDB, we need to assign the administrative rights to the user. For assigning the administrative rights to the end user, select the permissions tag for the user and click on Attach User Policy button.
  8. From the Manage User Permission policy, select the option Administrative access.
  9. Click on the apply policy to make the changes in users permission.
3. Download SDK

For accessing the AWS services, download the AWS SDK using the following link: http://aws.amazon.com/sdkforandroid/. This is a zip file, containing API libraries for accessing the AWS SimpleDB database. We need to import this library in the Android project in the next steps.

4. Creating a new Project

After completing the required configuration, it’s time to start our project.

In this project, we are going to create an application for the Movie database. This application will allow user to store the movie information in the SimpleDB and allow user to retrieve the movie information from the simpleDB.

First, we will complete the project configuration for the SimpleDB access and then we will see how to call the various SimpleDB API from the Android project.

Project Configuration

  1. In Eclipse, create a new project by going to File -> New -> Android Application Project and fill the required details. I kept my project name as SimpleDBTest and package name as com.simpledb.info
  2. Now we need to add the AWS Android SDK to our Android project.
    1. Right click on the libs folder of the project and select the import option.
    2. From the import form, select the General-> File System option.
    3. From the File System form, click the browse button and provide the path of the SDK downloaded in step 3. Path e.g. “C:\...\aws-android-sdk-1.7.1.1\aws-android-sdk-1.7.1.1\lib”.
    4. Now from the left list of the import form, select the option aws-android-sdk-1.7.1.1-debug.jar option.
    5. Click the finish button on the Import form to add selected jar file in Android project.
  3. AWS SimpleDB needs an Internet permission so add internet permission code in AndroidManifest.xml file.
  4. Now we need to store the Access Key Id and Secret Access Key in Android project. For that, create new property file as follows and store Access Key Id and Secret Access Key.
    1. Select src->com.simpledb.info (Package name) -> (right click) New -> File give File name as credential.properties.
    2. Access Key Id and Secret Access Key are the keys that we downloaded in step 2. Open credentials.csv file that we obtained from step 2 and copy Access Key Id and Secrete key Id.
    3. In the credential.properties file, add Access Key Id and Secret Access Key as follows:
    XML
    accessKey=xxxxxxxxxxxxxxxxx
    secreteKey=yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
  5. In this project, we are going to create three activities:
    1. Main Activity: This is main activity which shows the option to store and read movie information.
    2. Store Activity: This activity collects the movie information from the user and stores it into the SimpleDB.
    3. Read Activity: This activity retrieves all the movie information stored in the domain and shows it to the user.

Code for the above activities can be found in the attached project zip file.

SimpleDB API Call

A. Create an Amazon SimpleDB Connection

To create a SimpleDB Connection, create separate connection.java class file. In this code, getProperties function is used to retrieve the access key and secret key that is stored in the credentials.properties file. getAwsSimpleDB function provides the Credentials to the AWS web service and returns the created SiimpleDB object.

Java
package com.simpledb.info;

import java.util.Properties;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;

public class Connection {
    public static AmazonSimpleDB awsSimpleDB;
    public static Properties properties;

    // 1. Get Simple DB connection.
    public static AmazonSimpleDB getAwsSimpleDB()
    {
        if(awsSimpleDB==null)
        {
            BasicAWSCredentials credentials= new BasicAWSCredentials(getProperties().getProperty("accessKey"), Connection.getProperties().getProperty("secreteKey"));
            awsSimpleDB= new AmazonSimpleDBClient(credentials);
        }
        return awsSimpleDB;
    }
    
    public static Properties getProperties()
    {
        if(properties==null)
        {
            properties=new Properties();
            try {
                properties.load(StoreToDB.class.getResourceAsStream("credentials.properties"));
                
            } catch (Exception e) {
                // TODO: handle exception
            }        }
        return properties;    
    }
}

B. Create a Domain & Store Data to Domain

Domain in the simpleDB is same as table. In project, we created the StoreToDB class for storing row in the domain.

Java
public static void saveMovie(String name, float rating, String description)
    {
        try {

             Connection.getAwsSimpleDB().createDomain(new CreateDomainRequest( "movie_info"));
             List<ReplaceableAttribute> attribute= new ArrayList<ReplaceableAttribute>(1);
             attribute.add(new ReplaceableAttribute().withName("movieName").withValue(name));
             attribute.add(new ReplaceableAttribute().withName("movieRating").withValue(Float.toString(rating)));
             attribute.add(new ReplaceableAttribute().withName("movieDescription").withValue(description));
             Connection.awsSimpleDB.putAttributes(new PutAttributesRequest("movie_info",name, attribute));
            
        } catch (Exception e) {
                System.out.println(e.getMessage());
        }
    }    

C. Retrieve Stored Data from Domain

For retrieving the stored data from the domain, we have created ReadFromDB.java class. For retrieving the data, we need to create the SelectRequest which returns the list of rows in item list format.

In this project, we are retrieving all rows from the table, we can retrieve the particular row from the domain by using where condition on particular attribute.

To separate the particular field, we use the attribute name as filter as follows:

Java
public static Movie [] getAllMovies() throws Exception
    {
        SelectRequest selectRequest=  new SelectRequest("select * from movie_info").withConsistentRead(true);
        
        List<com.amazonaws.services.simpledb.model.Item> items  = Connection.getAwsSimpleDB().select(selectRequest).getItems();
        
        try
        {
        com.amazonaws.services.simpledb.model.Item temp1;
        int size= items.size();
        Movie [] movieList= new  Movie[size];
        
        for(int i=0; i<size;i++)
        {
            temp1= ((com.amazonaws.services.simpledb.model.Item)items.get( i ));
            
            List<com.amazonaws.services.simpledb.model.Attribute> tempAttribute= temp1.getAttributes();
            movieList[i]= new Movie();
            for(int j=0; j< tempAttribute.size();j++)
            {
                if(tempAttribute.get(j).getName().equals("movieName"))
                {
                    movieList[i].movieName=tempAttribute.get(j).getValue();
                }
                else if(tempAttribute.get(j).getName().equals("movieDescription"))
                {
                    movieList[i].movieDesctiption =tempAttribute.get(j).getValue();
                }
                else if(tempAttribute.get(j).getName().equals("movieRating"))
                {
                    movieList[i].movieRating =Float.valueOf(tempAttribute.get(j).getValue());                    
                }
            }
        }
        return movieList;
        }
        catch( Exception eex)
        {
            throw new Exception("FIRST EXCEPTION", eex);
        }
    }

Conclusion

Amazon SimpleDB service is a low touch, highly available, flexible and simple to use service for the small database application. SimpleDB application can be included in many other applications like logging, auditing, tracking application, etc. With Amazon SimpleDB, you can focus on application development without worrying about infrastructure.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)