2017-03-08 18 views
0

我從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(); 
    } 
} 
+0

在上面提到的鏈接中 - 有兩種解決方案:1)列表對象中的靜態字段2)意外地將相同的對象添加到列表中。我沒有提到靜態數組列表,當我輸入日誌時,它按預期打印 –

+0

這是第二個。您將同一個對象反覆添加到列表中,但每次您記錄它時,它都會更新爲最新值。 –

回答

0

您只創建了一個HashMap,那麼添加它(jsonAr.length())多次的卡洛斯。您只是多次向同一對象添加「引用」。如果你想讓它不同,你需要創建一個新對象。所有這些引用將隨着該對象中的數據更改而「更新」。

非常清楚,每個迴路是簡單地改變值mapping並添加另一個引用它carList

移動

mapping=new HashMap<>(); 

你對()循環中,然後看看會發生什麼。

+0

添加了我正在完成的完整異步任務 - –

+0

除非發生真正的混亂事件,否則我的答案仍然存在。您通過引用傳遞一個對象,並期望它按照價值發展。 – mstorkson

+0

在循環內移動映射 - 正在工作。謝謝 –