【发布时间】:2015-01-21 12:55:53
【问题描述】:
我在让我的 JSONObject 之一显示在 ListView 中时遇到了一些问题。我正在使用标准的 JSON Parser、Async Task 等,除了一个特定的字符串(即总数)之外的所有内容都可以正常工作。这是我的代码 sn-ps:
JSON:
{
"item": "Item name",
"quantity": "67",
"unit": "m",
"total": "603.00"
},
安卓:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_ITEMS);
for (int a = 0; a < items.length(); a++) {
JSONObject l = items.getJSONObject(a);
String item = l.getString(TAG_ITEM_NAME);
String unit = l.getString(TAG_UNIT);
String total = l.getString(TAG_TOTAL);
String quantity = l.getString(TAG_QUANTITY);
Log.d("item got: ", "> " + item);
Log.d("unit got: ", "> " + unit);
Log.d("total got: ", "> " + total);
Log.d("qty got: ", "> " + quantity);
HashMap<String, String> myItems = new HashMap<String, String>();
myItems.put(TAG_ITEM_NAME, item);
myItems.put(TAG_UNIT, unit);
myItems.put(TAG_TOTAL, total);
myItems.put(TAG_QUANTITY, quantity);
itemList.add(myItems);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(ItemsActivity.this,
itemList, R.layout.item_list_item,
new String[] { TAG_ITEM_NAME, TAG_UNIT, TAG_TOTAL, TAG_QUANTITY },
new int[] { R.id.itemName, R.id.unit, R.id.total, R.id.quantity});
setListAdapter(adapter);
}
XML:
<TextView
android:id="@+id/itemName"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/total"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/unit"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
现在,根据日志,所有四个都是“得到”,但是当我尝试将它们放入我的 ListView 时,总数(十进制数字)将不会显示。单个数字和其他非十进制数字显示完美,JSON中都是字符串,为什么我不能显示我的总数?
困惑...
【问题讨论】:
-
你能说明你是如何展示你的价值观的吗?我闻到一个错字。
-
@Marius,请查看编辑
-
@Marius - 我是个白痴!我发布的代码不是实际代码,但您在正确的区域。其中一个 XML TextViews 与 R.id.total 不匹配,因此在快速更改后,它可以完美显示。感谢您引导我朝着正确的方向前进!
-
我建议你下次重写适配器的
getView方法,这样你就可以更好地控制你的 textViews 发生的事情,还有一些拼写检查 - findViewById(someWrongId).someMethod(); -> NPE。另外,如果我没记错的话,您可以adapter.notifyDataSetChanged()避免重新创建适配器。 -
谢谢马吕斯。我想我离代码太近了,我没有看到问题。
标签: android json android-listview