2011-07-14 44 views
1

我有一個名單,我將使用add(int,Object)方法的價值,但是當我使用get(int)方法我得到相同的值就是最後添加值列表是給repited價值

檢索值

任何人都可以給予適當的建議? 見代碼。

公共靜態列表getCompanyName(字符串USER_ID){

List<CustomerList> fetchDatefromID = new ArrayList<CustomerList>(); 
    CustomerList tempProgram = new CustomerList(); 
    String result = ""; 
    InputStream is = null; 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("q", "" + user_id)); 

    // http post 
    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(
       "https://erestaurantonline.co.uk/kernow_mobile/customer_search.php?"); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
    } catch (Exception e) { 
     Log.e("log_tag", "Error in http connection " + e.toString()); 
    } 
    // convert response to string 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     result = sb.toString(); 
    } catch (Exception e) { 
     Log.e("log_tag", "Error converting result " + e.toString()); 
    } 

    // parse json data 
    try { 
     JSONArray jArray = new JSONArray(result); 
     for (int i = 0; i < jArray.length(); i++) { 
      JSONObject json_data = jArray.getJSONObject(i); 

      if (json_data.getString("company") != null) { 
       tempProgram.setCompanyName(json_data.getString("company")); 
       tempProgram.setID(json_data.getString("id")); 
       fetchDatefromID.add(i, tempProgram); 
      } 

     } 

    } catch (JSONException e) { 
     Log.e("log_tag", "Error parsing data " + e.toString()); 
    } 

    for (int i = 0; i < fetchDatefromID.size(); i++) { 
     Log.v("log_tag","DataMy : "+fetchDatefromID.get(i).getCompanyName().toString()); 
    } 
    return fetchDatefromID; 
} 

回答

1

嘗試更換

if (json_data.getString("company") != null) { 
       tempProgram.setCompanyName(json_data.getString("company")); 
       tempProgram.setID(json_data.getString("id")); 
       fetchDatefromID.add(i, tempProgram); 
      } 

隨着

if (json_data.getString("company") != null) { 
       tempProgram = new CustomerList(); 
       tempProgram.setCompanyName(json_data.getString("company")); 
       tempProgram.setID(json_data.getString("id")); 
       fetchDatefromID.add(i, tempProgram); 
      } 

否則每個項目在列表中被引用同一個對象,因此將永遠包含您最後放入它的任何數據。

+0

好的,謝謝朋友問題再次感謝,再次感謝 –