2014-10-05 50 views
0

我有一個JSON對象的JSONArray,每個JSON對象都是一個帶有「kind」鍵的字符串。我試圖通過JSONarray循環,並通過「kind」組織它們來填充SeperatedListAdapter。我試圖做到的,是這種結構Android for-loop陷入無盡循環

{ 
    communications[ 
     { "header":"kind" 
      communications[ 
      {} 
      {} 
      {} 
      {} 
      ] 

     } 

     { "header":"kind" 
      communications[ 
      {} 
      {} 
      {} 
      {} 
      ] 

     } 

    ] 


} 

我遇到的問題是for循環我已經創建了實現這一目標的陷入無限循環得到,因此崩潰的應用程序。有誰知道我在哪裏出了問題?

這裏是我的代碼,我知道它陷在一個循環,因爲它運行日誌「1」的約1000倍,即使我知道,只有5我傳遞的數組中的東西。

for(int i = 0; i < communicationsFromFile.length(); i++){ 
       JSONObject communication = communicationsFromFile.getJSONObject(i); 
       Log.v("Communications", "kind = " + communication.getString("kind")); 
       Log.v("Communications", "newComArray = " + newComArray); 
       if(newComArray.length() != 0){ 
        Log.v("Communications", "newComArray IsNotempty"); 

        for(int a = 0; a < newComArray.length();a++){ 
         JSONObject itemInArray = newComArray.getJSONObject(a); 
         JSONArray communicationsForKind = itemInArray.getJSONArray("communications"); 

         Log.v("Communications", "1"); 

         if(itemInArray.getString("header").equals(communication.getString("kind"))){ 
          Log.v("Communications", "Header Exists"); 
          communicationsForKind.put(communication); 
          itemInArray.put("communications", communicationsForKind); 
          newComArray.put(itemInArray); 


         }else{ 
          Log.v("Communications", "Header Does not Exist"); 
          JSONObject addItemInArray = new JSONObject(); 
          JSONArray addArrayToItem = new JSONArray(); 
          addArrayToItem.put(communication); 
          addItemInArray.put("header", communication.getString("kind")); 
          addItemInArray.put("communications", addArrayToItem); 

          newComArray.put(addItemInArray); 
         } 

        } 

       }else{ 

        JSONObject addItemInArray = new JSONObject(); 
        JSONArray addArrayToItem = new JSONArray(); 
        addArrayToItem.put(communication); 
        addItemInArray.put("header", communication.getString("kind")); 
        addItemInArray.put("communications", addArrayToItem); 
        newComArray.put(addItemInArray);  

       } 
     } 

回答

1

在inner for循環的每次迭代中,您將新對象放入newComArray。條件a < newComArray.length()始終滿足,因爲a和數組長度都以相同的速率增長。

+0

感謝您的幫助,你可以解釋更高我不知道你的意思 – iamlukeyb 2014-10-05 12:34:02

+0

我想通了,我改變了neComArray到orignal數組 – iamlukeyb 2014-10-05 13:12:13