如何从Android更新DynamoDB中的项目?

时间:2018-06-22 03:17:49

标签: java android amazon-dynamodb

标题描述了困扰我三天的问题。如何从Android应用程序更新DynamoDB中存储的项目?

在下面,我留下了已经检查并实现失败的链接列表:

1-https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-dynamodb-items.html 结果:严格来说,它仅适用于Java ee,而不是android

2-{{​​3}} 结果:即使“ unique-user-id”参数显然是唯一的,也会创建一个新项目

3-https://docs.aws.amazon.com/aws-mobile/latest/developerguide/add-aws-mobile-nosql-database.html#add-aws-mobile-nosql-database-crud-update 结果:同上,创建一个新的

4-https://docs.aws.amazon.com/aws-mobile/latest/developerguide/how-to-nosql-integrate-an-existing-table.html 结果:检索但创建一个新项目

1 个答案:

答案 0 :(得分:0)

我做错了什么: -在要发送更新的对象中不包括我的sort(又称Range)键。

其余: 首先,获得您的DynamoDBClient,我强烈建议实现一个单例模式来调用它,在这种情况下,我使用了configuration.json:

AWSMobileClient.getInstance().initialize(NewPatientActivity.this).execute();
    AWSCredentialsProvider credentialsProvider = AWSMobileClient.getInstance().getCredentialsProvider();
    AWSConfiguration configuration = AWSMobileClient.getInstance().getConfiguration();
    // Add code to instantiate a AmazonDynamoDBClient
    AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(credentialsProvider);

然后像这样设置一个UpdateItemRequest:

//SET THE KEYS VALUES
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
            key.put("your-partition-key", new AttributeValue().withS(value));
            key.put("your-sort-key-if-exists", new AttributeValue().withS(value));
//SET VALUES TO REPLACE OLD ONES
 Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
            expressionAttributeValues.put(":val1",new AttributeValue().withN(value1));
            expressionAttributeValues.put(":val2", new AttributeValue().withS(value2));
/*
IF YOU WANT TO READ THE JUST-UPDATED ITEM, HAVE THIS READY
            ReturnValue returnValues = ReturnValue.ALL_NEW;

*/
//SET THE UPDATEITEMREQUEST
      UpdateItemRequest updateItemRequest = new UpdateItemRequest()
                    .withTableName("your-table-name")
                    //KEYS DEFINED ABOVE                        
                    .withKey(key)
                    //SET WHERE TO UPDATE
                    .withUpdateExpression("set attr1 = :val1, attr2 = :val2")
                .withExpressionAttributeValues(expressionAttributeValues)
                   //INDICATE TO RETURN UPDATED ITEM                     
                  .withReturnValues(returnValues);
   //GET THE RESULT OF YOUR UPDATE AND EXECUTE IT
     UpdateItemResult result = your-dynamo-client.updateItem(updateItemRequest);
    //convert it to a string                
     Gson gson = new Gson();
     String x = gson.toJson(result);
    //Check it out                
     Log.e("RESULT :",x);

有关更多信息,我阐述了this的要点。