ArrayList Hashmap空指针异常

时间:2016-01-22 06:36:53

标签: java android hashmap

我在最后一句话中得到NullPointerException。请帮忙。

ArrayList<HashMap<String, String>> contactList;
for(int i=0; i < jsonArray.length(); i++){
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    HashMap<String,String> contact = new HashMap<String,String>();
    contact.put(TAG_ID, jsonObject.optString("id").toString());
    contact.put(TAG_NAME,jsonObject.optString("name").toString());
    contact.put(TAG_EXT,jsonObject.optString("extension").toString());
    contactList.add(contact);
}

4 个答案:

答案 0 :(得分:1)

您尚未初始化contactList。

 ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

答案 1 :(得分:0)

您尚未初始化contactList,应在使用前初始化

ArrayList<HashMap<String, String>> contactList=new ArrayList<HashMap<String, String>>();

答案 2 :(得分:0)

ArrayList应首先进行初始化。试试这个,

ArrayList<HashMap<String, String>> contactList;
 ArrayList<HashMap<String, String>> contactList=new ArrayList<HashMap<String, String>>();
 for(int i=0; i < jsonArray.length(); i++){
 JSONObject jsonObject = jsonArray.getJSONObject(i);
 HashMap<String,String> contact = new HashMap<String,String>();
 contact.put(TAG_ID, jsonObject.optString("id").toString());
 contact.put(TAG_NAME,jsonObject.optString("name").toString());
 contact.put(TAG_EXT,jsonObject.optString("extension").toString());
 contactList.add(contact);
}

答案 3 :(得分:0)

您必须初始化contactList `

ArrayList<HashMap<String, String>> contactList=new ArrayList<HashMap<String, String>>();
 for(int i=0; i < jsonArray.length(); i++){
 JSONObject jsonObject = jsonArray.getJSONObject(i);
 HashMap<String,String> contact = new HashMap<String,String>();
 contact.put(TAG_ID, jsonObject.optString("id").toString());
 contact.put(TAG_NAME,jsonObject.optString("name").toString());
 contact.put(TAG_EXT,jsonObject.optString("extension").toString());
 contactList.add(contact);
}`