2016-09-15 143 views
0

我有一個從服務器返回的信息列表,我將它放在名爲「items」的數組列表中。我想知道如何只提取部門並將它們放入一個簡單的字符串數組中,我已將其命名爲部門列表。向android中的數組添加元素

這是列表的樣子

[ 
    { 
"Department": "Mobile Development", 
    "Department": 22 
    }, 
    { 
    " "Department": "IT Support", 
    "Department": 13 
    }] 

這是我迄今編碼,但是我覺得有一個與我想在我的添加對每個方式有問題。

private void loadCompanyInfo() { 
    //final Context context = this.getActivity(); 
    final Context context = this.context; 
     Organization client = new Organization(context); 

     Organization.api(context).getCompanyInforamtion(client.getID()).enqueue(new Callback<Results<CostCentresResult>>() { 
     @Override 
     public void onResponse(Call<Results<CostCentresResult>> call, Response<Results<CostCentresResult>> response) { 
      if (response.isSuccessful()) { 
       try { 
        Items = new ArrayList<>(); 
        companyInfoList = new ArrayList<>(); 

        Items.addAll(response.body()); 
        if(Items.contains("Department")) { 
        Items.get(Items.indexOf(0)); 

        for (int i = 0; i < Items.size(); i++) { 
         companyInfoList.add(Items[0]) 
        } 

        } 

       } catch (Exception ex ) { 
        ex.printStackTrace(); 
        ex.getMessage(); 
        ex.getCause(); 
        ex.getClass(); 
       } 
      } 
     } 
     @Override 
     public void onFailure(Call<Results<CostCentresResult>> call, Throwable t) { 
// TODO: handle ex 
      Errors.handleException(t); 
     } 

     }); 
    } 

} 
+0

能否請你把你的POJO類在這裏? –

+0

你的JSON是錯的 – Nikhil

+0

我其實只是想知道如何從第一個arraylist(Items)中提取部門並將它們添加到另一個ArrayList(companyInfoList)中; – Zidane

回答

0

下面的代碼將幫助您從您的服務器響應得到主管部門的名單:

try { 
      ArrayList<String> mDepartmentList = new ArrayList<String>(); 
      JSONArray serverResponseJsonArray = new JSONArray(response.body()); 
      if (serverResponseJsonArray != null 
        && serverResponseJsonArray.length() > 0) { 
       for (int i = 0; i < serverResponseJsonArray.length(); i++) { 
        JSONObject departmentJsonObj = serverResponseJsonArray 
          .getJSONObject(i); 
        if (departmentJsonObj != null 
          && !departmentJsonObj.equals("")) { 
         if (departmentJsonObj.has("Department")) { 
          mDepartmentList.add(departmentJsonObj 
            .getString("Department")); 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     }