2013-01-24 26 views
1

在logcat中,我爲此代碼示例獲取null pointer exception。我試圖在Arraylist內添加例如oneObject.has(TAG_TITLE),但是當我打印currentPost.getid()時,例如,我得到這個nullpointer excepttion。有人能幫助我嗎。向ArrayList中添加數據android

//正從URL

JSONArray jArray = jParser.getJSONFromUrl(url); 
ArrayList<Post> PostList = new ArrayList<Post>(); 
Post currentPost = new Post(); 

// looping through All element 
for(int i = 0; i < jArray.length(); i++){ 
    try{ 
     JSONObject oneObject = jArray.getJSONObject(i); 
     // Storing each json item in variable 
     if(oneObject.has(TAG_ID)){ 
      id = oneObject.getString(TAG_ID); 
      currentPost.setId(id); 
     } 
     else{ 
      id=""; 
     } 
     if(oneObject.has(TAG_TITLE)){ 
      title = oneObject.getString(TAG_TITLE); 
      currentPost.setTitle(title); 
     } 
     else{ 
      title =""; 
     } 
     if(oneObject.has(TAG_CONTENT)){ 
      content = oneObject.getString(TAG_CONTENT); 
      currentPost.setContent(content); 
     } 
     else{ 
      content =""; 
     } 
     System.out.println("postlist: "+currentPost.getId()); 
     PostList.add(currentPost); 
     currentPost = new Post(); 

回答

1

你還需要設置currentPost對象的字段值設置爲默認值,如果在JSON字符串不存在的鍵名:

  // your code here... 
      if(oneObject.has(TAG_ID)){ 

       id = oneObject.getString(TAG_ID); 

       currentPost.setId(id); 
      } 
      else{ 

       id="DEFAULT_VALUE"; 
       currentPost.setId(id); //<<<< set default value here 
      } 
      // your code here... 
+0

嗨imrank,它仍然爲空 – Dimitri

+0

@sophia:把'currentPost.setId(id); System.out.println(「postlist:」+ currentPost.getId());'代碼裏面的其他部分,並檢查你是否獲得價值登錄或不是 –

+0

是的,它是非常感謝你 – Dimitri

0

JSON字符串在代碼

// Storing each json item in variable 

        if(oneObject.has(TAG_ID)){ 

         id = oneObject.getString(TAG_ID); 

         currentPost.setId(id); 
        } 
        else{ 

         id=""; 
        } 

你已經錯過了設定的ID爲當前oneObject.has(TAG_ID)返回false。

避免這種情況的最佳方法是如果未設置參數,則返回所有獲取者的空字符串。

編輯:

添加使用粗體的更改。

//保存在變量

    if(oneObject.has(TAG_ID)){ 

         id = oneObject.getString(TAG_ID); 

         currentPost.setId(id); 
        } 
        else{ 

         id=""; 
         **currentPost.setId(id);** 
        } 
每個JSON項目
+0

我不請理解,請詳細說明 – Dimitri

+0

如果'oneObject.has(TAG_ID)'爲真,則通過調用'currentPost.setId(id)'來設置帖子ID,但當它爲假時不設置。檢查我的回答我編輯它。 – Supreethks