我正在使用相同的代码/示例在 android 中学习 JSON 及其解析
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
但是在实现和运行时给出空指针异常
在开启 JSON 时 contacts = json.getJSONArray(TAG_CONTACTS);
JSONArray contacts = null;
private static String url = "http://api.androidhive.info/contacts/";
public void initParsing()
{
ListView listView = (ListView) findViewById(R.id.listView_song);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
System.out.println("---getJSON");
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
System.out.println("---times");
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// 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_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// ListAdapter adapter = new SimpleAdapter(this, contactList,
// R.layout.list_item,
// new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
// R.id.name, R.id.email, R.id.mobile });
// setListAdapter(adapter);
// listView.setAdapter(new CustomArrayAdapter(this, TAG_NAME)); // setting the adapter
}