2013-08-19 147 views
0

這個問題相當簡單,但無法讓我的腦袋圍繞它。在api中通過hashMaps循環訪問

以下API是要處理

{ "data" : [ { "id" : "102", 
     "sector" : "projectSector1", 
     "title" : "projectTitle1" 
     }, 
     { "id" : "100", 
     "sector" : "projectSector2", 
     "title" : "projectTitle2" 
     }, 
     { "id" : "98", 
     "sector" : "projectSector3", 
     "title" : "projectTitle3" 
     } 
    ], 
    "status" : "success" 
} 

所以在我doInBackground我運行下面的代碼:

protected Void doInBackground(Void... params) { 
      UserFunctions user = new UserFunctions(); 
      JSob = user.allprojects(); 
      try { 
       JSar = JSob.getJSONArray("data"); 

      } catch (JSONException e1) { 
       e1.printStackTrace(); 
      } 
      for(int i=0; i<JSar.length(); i++){ 
       try { 
        JSONObject newobj = JSar.getJSONObject(i); 
        project_title = newobj.getString("title"); 
        project_sector = newobj.getString("sector"); 

        all_list.put("title", project_title); 
        all_list.put("sector", project_sector); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } 
      return null; 
     } 

在這裏,我想HashMap(該all_list是HashMap中)的「扇區」和「標題」作爲關鍵字,並將它們的相應值作爲值輸入。但由於某種原因,我只能獲取projectTitle3和projectSector3兩次。請幫忙 !

+0

我認爲,這樣做,你覆蓋在HashMap中 – Pavlos

+0

@Pavlos鍵的以前的值可能是什麼是一個好的解決方案? –

+0

有人在下面回答你!在你的情況下,我會使用數據庫!特別是如果json很長! – Pavlos

回答

2

你可以做如下

//Create a list of hashmap 
ArrayList<HashMap<String, String>> lst = new ArrayList<HashMap<String, String>>(); 

//in doInBackground method 
HashMap<String, String> all_list = new HashMap<String, String>();      
all_list.put("title", project_title); 
all_list.put("sector", project_sector); 
lst.add(map); 
+0

如果我使用這個ArrayList ...我怎麼能爲這個活動使用的listView創建一個CustomAdapter? –

+0

@ user2247689你可以查看本教程http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/ –

+0

以及這是我已經實現,但我有一個複選框,所以需要CustomAdapter來啓用listView點擊和checkBox點擊。 –

1

它是因爲你用你的HashMap中的相同鍵值覆蓋了值。您應該爲每個循環迭代使用不同的密鑰。

您也可以使用鍵進行聯合。

對於防爆:

for(int i=0; i<JSar.length(); i++){ 
       try { 
        JSONObject newobj = JSar.getJSONObject(i); 
        project_title = newobj.getString("title"); 
        project_sector = newobj.getString("sector"); 

        all_list.put("title"+i, project_title); 
        all_list.put("sector"+i, project_sector); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } 
1

不能存儲HashMap相同的密鑰。其實你可以但只有最後一把鑰匙纔會被儲存在。HashMap只有商店唯一鍵。這是你只有兩把鑰匙的原因。

要解決它,這樣做:

for(int i=0; i<JSar.length(); i++){ 
      try { 
       JSONObject newobj = JSar.getJSONObject(i); 
       project_title = newobj.getString("title"); 
       project_sector = newobj.getString("sector"); 

       all_list.put("title" + i, project_title); 
       all_list.put("sector" + i, project_sector); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     }