joseph wallberg joseph wallberg - 3 months ago 48x
Android Question

Query from AWS DynamoDB for Android

I am trying to fetch data from my AWS DynamoDB database. I have the following code set up, however I am getting errors. Unclear how to proceed from here in order to query the data based on primary key

import android.os.Bundle;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.*;

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {

CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
"**********************", // Identity Pool ID
Regions.US_EAST_1 // Region

AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);


First comment, it looks like you are trying to this in an Activity -- this will definitely throw Network on Main Thread exception in Android.

Second, as a general guide, you need to set up a separate class with your DynamoDB fields set up and linked to variables in the class. For example:

@DynamoDBTable(tableName = SA_AWSConstants.QUESTIONTABLENAME)
public class SA_Question implements Comparable<SA_Question> {

    // fields coming from AWS table
    private String questionguid_str; // : STRING, PRIMARY HASH KEY
    private String json_str;
    private long ordinalposition_int;


    @DynamoDBHashKey(attributeName = SA_AWSConstants.DBSCHEMA_QUESTIONGUID)
    public String getQuestionguid_str() {
        return questionguid_str;

    public void setQuestionguid_str(String questionguid_str) {
        this.questionguid_str = questionguid_str;

    @DynamoDBRangeKey(attributeName = SA_AWSConstants.DBSCHEMA_ORDINALPOS)
    public long getOrdinalposition_int() {
        return ordinalposition_int;

    public void setOrdinalposition_int(long ordinalposition_int) {
        this.ordinalposition_int = ordinalposition_int;

    @DynamoDBAttribute(attributeName = SA_AWSConstants.DBSCHEMA_QUESTION_JSONSTR)
    public String getJson_str() {
        return json_str;

    public void setJson_str(String json_str) {
        this.json_str = json_str;

Then you can do something like this:

                DynamoDBMapper mapper = new DynamoDBMapper(ddb);
                DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();

                PaginatedScanList<SA_Question> paginatedq = mapper.scan(SA_Question.class, scanExpression);
                ArrayList<SA_Question> awsqlist = new ArrayList<SA_Question>();

                for (SA_Question q : paginatedq) {

You have to be mindful of the limits AWS sets on returns of data with a single query (hence the PaginatedScan -- if you expect to exceed the limit then you will need to check whether more data exists to be returned).