我想将用户写入的文本框中的新项目放入 DynamoDB 的现有表中。但是,我遇到了一些我不太了解的错误。以下是我的代码:
添加方法
public class Add_Item
{
private String title;
private AmazonDynamoDBClient client;
String tableName = "Tesis_FTSM";
public void DynamoDBLoad() throws IOException
{
AWSCredentials credentials = new PropertiesCredentials(DynamoDBClient.class.getClassLoader().getResourceAsStream("AWSCredentials.properties"));
client = new AmazonDynamoDBClient(credentials);
client.setRegion(Region.getRegion(Regions.US_WEST_2));
}
public void add()
{
final EditText title = (EditText)findViewById(R.id.text1);
String tajuk = title.getText().toString();
Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
try {
item.put("Id", new AttributeValue().withS(tajuk));
PutItemRequest itemRequest = new PutItemRequest().withTableName(
tableName).withItem(item);
client.putItem(itemRequest);
item.clear();
} catch (Exception e) {
System.err.println("Create items failed.");
System.err.println(e.getMessage());
}
}
主活动
public class Task extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Looper.prepare();
try
{
Add_Item db = new Add_Item();
db.DynamoDBLoad();
db.add();
} catch (Exception e)
{
e.printStackTrace();
}
Looper.myLooper().quit();
return null;
}
protected void onPostExecute(String page)
{
//onPostExecute
}
}
日志猫错误
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕java.lang.NullPointerException
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at android.app.Activity.findViewById(Activity.java:1957)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at com.af.ftsm.testing.Add_Item.<init>(Add_Item.java:26)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at com.af.ftsm.testing.MainActivity$Task.doInBackground(MainActivity.java:50)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at com.af.ftsm.testing.MainActivity$Task.doInBackground(MainActivity.java:39)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-15 10:33:33.938 16885-17179/com.af.ftsm.testing W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
我向表中添加项目的方法是否错误或其他方法?谢谢。
根据这些信息,我相信资源 R.id.text1 不存在,所以 findViewById 返回 null。在 null 上强制转换的类型将引发 NPE。如果没有,请告诉我们Add_Item.java的第 26 行的内容。
PS:您最好避免在生产级Android应用程序中使用PropertiesCredentials。 CognitoCachingCredentialsProvider是获取AWS凭证的推荐方法。有关更多详细信息,请参阅亚马逊认知身份。