Menu
AWS Mobile
Developer Guide

Add NoSQL Database to Your Mobile App with Amazon DynamoDB

Overview

The AWS Mobile Hub nosqldb feature uses Amazon DynamoDB to enable you to create database tables that can store and retrieve data for use by your apps.

Set Up Your Backend

  1. Complete the Get Started steps before you proceed.

  2. Enable NoSQL Database: Open your project in Mobile Hub and choose the NoSQL Database tile to enable the feature.

  3. Follow the console work flow to define the tables you need. See Configuring the NoSQL Database Feature for details.

  4. When the operation is complete, an alert will pop up saying "Your Backend has been updated", prompting you to download the latest copy of the cloud configuration file. If you're done configuring the feature, choose the banner to return to the project details page.

  5. From the project detail page, every app that needs to be updated with the latest cloud configuration file will have a flashing Integrate button. Choose the button to enter the integrate wizard.

  6. Update your app with the latest copy of the cloud configuration file. Your app now references the latest version of your backend. Choose Next and follow the NoSQL Database documentation below to connect to your backend.

  7. Download the models required for your app. The data models provide set and get methods for each attribute of a DynamoDB table.

Connect to your backend

To add AWS Mobile NoSQL Database to your app

Android - JavaiOS - Swift
Android - Java
  1. Set up AWS Mobile SDK components with the following Set Up Your Backend steps.

    1. app/build.gradle must contain:

      dependencies{ implementation 'com.amazonaws:aws-android-sdk-ddb-mapper:2.6.+' }
    2. For each Activity where you make calls to perform database operations, import the following APIs.

      import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper;
  2. Create a DynamoDBMapper client for your app as in the following example.

    // import DynamoDBMapper import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper; public class MainActivity extends AppCompatActivity { // Declare a DynamoDBMapper object DynamoDBMapper dynamoDBMapper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Instantiate a AmazonDynamoDBMapperClient AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider()); this.dynamoDBMapper = DynamoDBMapper.builder() .dynamoDBClient(dynamoDBClient) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .build(); } }
  3. Add the project data model files you downloaded from the Mobile Hub console. The data models provide set and get methods for each attribute of a DynamoDB table they model.

    1. Copy the data model file(s) you downloaded, ./YOUR-PROJECT-NAME-integration-lib-aws-my-sample-app-android/src/main/java/com/amazonaws/models/nosqlYOUR-TABLE-NAMEDO.java into the Android Studio folder that contains your main activity.

Note

Use Asynchronous Calls to DynamoDB

Since calls to DynamoDB are synchronous, they don't belong on your UI thread. Use an asynchronous method like the Runnable wrapper to call DynamoDBObjectMapper in a separate thread.

Runnable runnable = new Runnable() { public void run() { //DynamoDB calls go here } }; Thread mythread = new Thread(runnable); mythread.start();
iOS - Swift
  1. Set up AWS Mobile SDK components with the following Set Up Your Backend steps.

    1. Podfile that you configure to install the AWS Mobile SDK must contain:

      platform :ios, '9.0' target :'YOUR-APP-NAME' do use_frameworks! pod 'AWSDynamoDB', '~> 2.6.13' # other pods end

      Run pod install --repo-update before you continue.

    2. Classes that call DynamoDB APIs must use the following import statements:

      import AWSCore import AWSDynamoDB
  2. From the location where you downloaded the data model file(s), drag and drop each file with the form of your-table-name.swift into the folder that contains your AppDelegate.swift. Select Copy items if needed and Create groups, if these options are offered.

Perform CRUD Operations

Create (Save) an Item

Use the following code to create an item in your NoSQL Database table.

Android - JavaiOS - Swift
Android - Java

These fragments are based on a table named News, with a partition key called userID and a sort key (rangekey) called articleId. The source of the NewsDO object is a data model file downloaded from a Mobile Hub project that enables a News table.

public void createNews() { final NewsDO newsItem = new NewsDO(); newsItem.setUserId(identityManager.getCachedUserID()); newsItem.setArticleId("Article1"); newsItem.setContent("This is the article content"); new Thread(new Runnable() { @Override public void run() { dynamoDBMapper.save(newsItem); // Item saved } }).start(); }
iOS - Swift

These fragments are based on a table named News, with a partition key called userID and a sort key (rangekey) called articleId. The source of the NewsDO object is a data model file downloaded from a Mobile Hub project that enables a News table.

func createNews() { let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default() // Create data object using data models you downloaded from Mobile Hub let newsItem: News = News() newsItem._userId = AWSIdentityManager.default().identityId newsItem._articleId = "YourArticleId" newsItem._title = "YourTitlestring" newsItem._author = "YourAuthor" newsItem._creationDate = NSDate().timeIntervalSince1970 as NSNumber //Save a new item dynamoDbObjectMapper.save(newsItem, completionHandler: { (error: Error?) -> Void in if let error = error { print("Amazon DynamoDB Save Error: \(error)") return } print("An item was saved.") }) }

Read (Load) an Item

Use the following code to read an item in your NoSQL Database table.

Android - JavaiOS - Swift
Android - Java
public void readNews() { new Thread(new Runnable() { @Override public void run() { NewsDO newsItem = dynamoDBMapper.load( NewsDO.class, identityManager.getCachedUserID(), "Article1"); // Item read // Log.d("News Item:", newsItem.toString()); } }).start(); }
iOS - Swift
func readNews() { let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default() // Create data object using data models you downloaded from Mobile Hub let newsItem: News = News(); newsItem._userId = AWSIdentityManager.default().identityId dynamoDbObjectMapper.load( News.self, hashKey: newsItem._userId, rangeKey: "YourArticleId", completionHandler: { (objectModel: AWSDynamoDBObjectModel?, error: Error?) -> Void in if let error = error { print("Amazon DynamoDB Read Error: \(error)") return } print("An item was read.") }) }

Update an Item

Use the following code to update an item in your NoSQL Database table.

Android - JavaiOS - Swift
Android - Java
public void updateNews() { final NewsDO newsItem = new NewsDO(); newsItem.setUserId(identityManager.getCachedUserID()); newsItem.setArticleId("Article1"); newsItem.setContent("This is the updated content."); new Thread(new Runnable() { @Override public void run() { dynamoDBMapper.save(newsItem); // Item updated } }).start(); }
iOS - Swift
func updateNews() { let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default() let newsItem: News = News(); newsItem._userId = AWSIdentityManager.default().identityId newsItem._articleId = "YourArticleId" newsItem._title = "This is the Title" newsItem._author = "B Smith" newsItem._creationDate = NSDate().timeIntervalSince1970 as NSNumber newsItem._category = "Local News" dynamoDbObjectMapper.save(newsItem, completionHandler: {(error: Error?) -> Void in if let error = error { print(" Amazon DynamoDB Save Error: \(error)") return } print("An item was updated.") }) }

Delete an Item

Use the following code to delete an item in your NoSQL Database table.

Android - JavaiOS - Swift
Android - Java
public void deleteNews() { new Thread(new Runnable() { @Override public void run() { NewsDO newsItem = new NewsDO(); newsItem.setUserId(identityManager.getCachedUserID()); //partition key newsItem.setArticleId("Article1"); //range (sort) key dynamoDBMapper.delete(newsItem); // Item deleted } }).start(); }
iOS - Swift
func deleteNews() { let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default() let itemToDelete = News() itemToDelete?._userId = AWSIdentityManager.default().identityId itemToDelete?._articleId = "YourArticleId" dynamoDbObjectMapper.remove(itemToDelete!, completionHandler: {(error: Error?) -> Void in if let error = error { print(" Amazon DynamoDB Save Error: \(error)") return } print("An item was deleted.") }) }

Perform a Query

A query operation enables you to find items in a table. You must define a query using both the hash key (partition key) and range key (sort key) attributes of a table. You can filter the results by specifying the attributes you are looking for.

The following example code shows querying for news submitted with userId (hash key) and article ID beginning with Trial (range key).

Android - JavaiOS - Swift
Android - Java
public void queryNews() { new Thread(new Runnable() { @Override public void run() { NewsDO news = new NewsDO(); news.setUserId(identityManager.getCachedUserID()); news.setArticleId("Article1"); Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.BEGINS_WITH) .withAttributeValueList(new AttributeValue().withS("Trial")); DynamoDBQueryExpression queryExpression = new DynamoDBQueryExpression() .withHashKeyValues(note) .withRangeKeyCondition("articleId", rangeKeyCondition) .withConsistentRead(false); PaginatedList<NewsDO> result = dynamoDBMapper.query(NewsDO.class, queryExpression); Gson gson = new Gson(); StringBuilder stringBuilder = new StringBuilder(); // Loop through query results for (int i = 0; i < result.size(); i++) { String jsonFormOfItem = gson.toJson(result.get(i)); stringBuilder.append(jsonFormOfItem + "\n\n"); } // Add your code here to deal with the data result Log.d("Query result: ", stringBuilder.toString()); if (result.isEmpty()) { // There were no items matching your query. } } }).start(); }
iOS - Swift
func queryNote() { // 1) Configure the query let queryExpression = AWSDynamoDBQueryExpression() queryExpression.keyConditionExpression = "#articleId >= :articleId AND #userId = :userId" queryExpression.expressionAttributeNames = [ "#userId": "userId", "#articleId": "articleId" ] queryExpression.expressionAttributeValues = [ ":articleId": "SomeArticleId", ":userId": AWSIdentityManager.default().identityId ] // 2) Make the query let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default() dynamoDbObjectMapper.query(News.self, expression: queryExpression) { (output: AWSDynamoDBPaginatedOutput?, error: Error?) in if error != nil { print("The request failed. Error: \(String(describing: error))") } if output != nil { for news in output!.items { let newsItem = news as? News print("\(newsItem!._title!)") } } } }