我從json中獲取數據並將其存儲在Asynctask中的ArrayList中(doinbackground) - 在添加到ArrayList後保持日誌並顯示所有項目正確。ArrayList <HashMap>總是返回上一個值
在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)列表對象中的靜態字段2)意外地將相同的對象添加到列表中。我沒有提到靜態數組列表,當我輸入日誌時,它按預期打印 –
這是第二個。您將同一個對象反覆添加到列表中,但每次您記錄它時,它都會更新爲最新值。 –