2016-01-22 68 views
-2

我在上一條語句中獲得NullPointerException。請幫助。ArrayList哈希表空指針異常

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); 
} 
+6

的[什麼是空指針異常,怎麼解決呢?(http://stackoverflow.com/questions/可能的複製218384/what-is-null-pointer-exception-and-how-do-i-fix-it) –

回答

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); 
}` 
0

你沒有初始化contactList,就應該使用

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

它很有效。非常感謝。 – hushan

0

ArrayList中應首先iitialized之前被初始化。試試這個,

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); 
} 
1

你還沒有初始化contactList。

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