我从JSONArray
获取数据,当它为空时,我需要显示一条说明无数据的文字。这是代码。执行此操作时出错。
List<NameValuePair> params = new ArrayList<NameValuePair>();
json = jParser.makeHttpRequest(url_all_events, "GET", params);
try {
events = json.getJSONArray(TAG_EVENTS);
if(events.length() == 0){
TextView txno = (TextView) findViewById(R.id.no_events);
txno.setVisibility(View.VISIBLE);
}else{
for (int i = 0; i < events.length(); i++) {
JSONObject c = events.getJSONObject(i);
id = c.getString(TAG_ID);
date = c.getString(TAG_DATE);
venue = c.getString(TAG_VENUE);
time = c.getString(TAG_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_DATE, date);
map.put(TAG_TIME, time);
map.put(TAG_VENUE, venue);
// adding HashList to ArrayList
eventList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
我得到的错误是:
04-17 15:55:54.335: E/JSON Parser(6199): Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
如何在收到空值时设置文本?
答案 0 :(得分:3)
虽然Alex van den Hoogen的回答是正确的,但我想指出有两种类似的方法可以从JSONObject
中提取值:
getJSONArray()
会抛出异常; optJSONArray()
返回null。你可以像这样使用后者:
events = json.optJSONArray(TAG_EVENTS);
if (events == null || events.length() == 0) {
TextView txno = (TextView) findViewById(R.id.no_events);
txno.setVisibility(View.VISIBLE);
} else {
...
}
答案 1 :(得分:1)
events
中events = json.getJSONArray(TAG_EVENTS);
的分配不起作用,因为没有JSONArray
而会抛出异常。
解决此问题的一种方法是在catch
子句中设置错误,如下所示:
List<NameValuePair> params = new ArrayList<NameValuePair>();
json = jParser.makeHttpRequest(url_all_events, "GET", params);
try {
events = json.getJSONArray(TAG_EVENTS);
if(events.length() == 0) {
throw new JSONException("Content was empty");
} else {
for (int i = 0; i < events.length(); i++) {
id = c.getString(TAG_ID);
date = c.getString(TAG_DATE);
venue = c.getString(TAG_VENUE);
time = c.getString(TAG_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_DATE, date);
map.put(TAG_TIME, time);
map.put(TAG_VENUE, venue);
// adding HashList to ArrayList
eventList.add(map);
}
}
} catch (JSONException e) {
TextView txno = (TextView) findViewById(R.id.no_events);
txno.setVisibility(View.VISIBLE);
}
当events JSONArray
中没有内容时,这也会引发异常。但是异常将被捕获并显示您已经设置的消息(我想)。