列表给出了重复的值

时间:2011-07-14 07:49:37

标签: android listview

我有一个列表,我正在使用add(int,Object)方法添加值但是当我使用get(int)方法检索值时,我得到的值是最后添加的值

任何人都可以给出适当的建议吗? 见代码。

public static List getCompanyName(String 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 个答案:

答案 0 :(得分: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);
            }

否则列表中的每个项目都引用同一个对象,因此将始终包含您最后放入的任何数据。