【发布时间】:2016-03-13 03:26:33
【问题描述】:
我想要做的是在特定的索引位置更改/替换 json 数组中的值。在查看 http://www.json.org/javadoc/org/json/JSONArray.html 的文档后,我发现 jsonArray 没有 getIndex() 方法。在这种情况下如何在给定的索引位置更新我的 json 数组。 这是在我的 android 代码中创建 json 数组的方法。
private void createJsonArray() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
String invNumber = textViewInvNo.getText().toString();
String bcode = barCode.getText().toString();
String description = itemDesc.getText().toString();
String wt = weightLine.getText().toString();
String rateAmt = rateAmount.getText().toString();
String making = makingAmount.getText().toString();
String netr = netRate.getText().toString();
String iTotal = itemtotal.getText().toString();
String vatAmt = textViewVat.getText().toString();
String sumAmt = textViewSum.getText().toString();
String crtDate = textViewCurrentDate.getText().toString();
try {
jsonObject.put("custInfo", custSelected.toString());
jsonObject.put("invoiceNo", invNumber);
jsonObject.put("barcode", bcode);
jsonObject.put("description", description);
jsonObject.put("weight", wt);
jsonObject.put("rate", rateAmt);
jsonObject.put("makingAmt", making);
jsonObject.put("net_rate", netr);
jsonObject.put("itemTotal", iTotal);
jsonObject.put("vat", vatAmt);
jsonObject.put("sum_total", sumAmt);
jsonObject.put("bill_type", billType);
jsonObject.put("date", crtDate);
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemSelectedJson.put(index, jsonObject);
index++;
} catch (JSONException e) {
e.printStackTrace();
}
}
这是我用来更新包含 json 对象的 json 数组的代码。
try {
itemSelectedJson.getJSONObject(i).put("net_rate",netChange);
Log.d("NETRATE_TW",itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
现在这段代码的问题是每次向代码中添加新项目时它都会更新 jsonArray。所以第一个对象的值与最后一个对象相同。
另外请注意,我在文本观察器中使用此代码。所以 afterTextchanged() 方法看起来像这样。
@Override
public void afterTextChanged(Editable s) {
String netChange = netRate.getText().toString();
final int row_id = (int) newRow.getTag();
if ((row_id<0) || (row_id> itemSelectedJson.length())){
return;
}
try {
itemSelectedJson.getJSONObject(row_id-1).put("net_rate",netChange);
Log.d("NETRATE_TW",itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
};
这是我的数据库的快照。
【问题讨论】:
-
这里的“newRow”是什么?
-
@Hitesh542 newRow 是我动态添加的表格行
-
@DroidDev 谢谢 :) 你能帮忙解答吗?