ArrayList <hashmap>始终返回最后一个值

时间:2017-03-08 20:44:06

标签: java android arraylist

我从json获取数据并存储在Asynctask(doinbackground)中的ArrayList中 - 在添加到ArrayList后保留一个日志,这会正确显示所有项目。

在onPostExecute中,我在不同位置打印少量ArrayList - 但它总是打印最后一个条目。

完整AsyncTask

的代码段下方
       public class GetTheCarList extends AsyncTask<Void,Void,Void>
{
    ProgressDialog progressDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog=ProgressDialog.show(getActivity(),"","Loading..");
    }

    @Override
    protected Void doInBackground(Void... params) {
        StringBuilder sb=new StringBuilder();
        BufferedReader br=null;

        try {
            br=new BufferedReader(new InputStreamReader(getActivity().getAssets().open("vehicles.json")));
            String temp;
            while((temp=br.readLine())!=null)
            {
                sb.append(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        finally {
            try {
                br.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }


        JSONArray jsonAr = null;
        try {
            jsonAr = new JSONArray(sb.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mapping=new HashMap<>();
        carList=new ArrayList<>();
        for(int i=0;i<=jsonAr.length();i++)
        {
            JSONObject jsonOb= null;
            try {
                jsonOb = jsonAr.getJSONObject(i);
                String year=jsonOb.getString("year");
                String make=jsonOb.getString("make");
                String model=jsonOb.getString("model");
                String mileage=jsonOb.getString("mileage");
                String icon=jsonOb.getString("image_url");


                mapping.put("year",year);
                mapping.put("make",make);
                mapping.put("model",model);
                mapping.put("mileage",mileage);
                mapping.put("image_url",icon);

                carList.add(mapping);
                Log.e("***", "carlist " + " " + carList.get(i)); // WORKS CORRECTLY

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


        }


        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        efficientAdapter=new EfficientAdapter();
            Log.e("***", "carlist " + " " + carList.get(17620)); // DISPLAYS LAST VALUE

        lvCarList.setAdapter(efficientAdapter);
        progressDialog.dismiss();
    }
}

1 个答案:

答案 0 :(得分:0)

您只创建了一个HashMap,然后多次将它(jsonAr.length())添加到您的carList中。您刚刚多次向同一对象添加了“引用”。如果希望它不同,则需要创建一个新对象。当该对象中的数据发生变化时,所有这些引用都将“更新”。

非常清楚,每个循环只是更改mapping中的值并向carList添加另一个引用

移动

mapping=new HashMap<>();
在你的for()循环中,然后看看会发生什么。