2017-02-12 86 views
0

我從php服務器中檢索JSON數組對象並在ListView上顯示它,我成功地能夠檢索數據並將其存儲到Arraylist中,但是當我試圖在ListView上顯示它時,只顯示最後一個項目多次。 我使用Volley回調界面來存儲數據, 和使用ListFragment。這裏是我的代碼:Listview只顯示每行中的最後一項?

Server.getDataFromServer(getActivity(), "product.php", new Server.VolleyCallback() { 
    @Override 
    public void onSuccessResponse(JSONArray jsonArray) { 
     try { 
      for(int i = 0; i<jsonArray.length(); i++){ 
       mProduct.setId(jsonArray.getJSONObject(i).getInt("mId")); 
       mProduct.setName(jsonArray.getJSONObject(i).getString("mName")); 
       mProduct.setPrice(jsonArray.getJSONObject(i).getDouble("mPrice")); 
       mProducts.add(mProduct); 

       System.out.println(mProducts.get(i)); 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
      ArrayAdapter<Product> adapter= new ArrayAdapter<>(getActivity(), R.layout.home_list_row, mProducts); 
      setListAdapter(adapter); 
     } 
    } 
); 

這裏是onCreateView

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_home, container, false); 
    listView = (ListView)rootView.findViewById(android.R.id.list); 
    return rootView; 
} 

android monitor

ListView

回答

0

您已經創建了只有一個產品的實例mProduct

每個設定裝置的previuos值重寫在mProducts您已經添加相同的實例3倍

for(int i = 0; i<jsonArray.length(); i++){ 
    mProduct.setId(jsonArray.getJSONObject(i).getInt("mId")); 
    mProduct.setName(jsonArray.getJSONObject(i).getString("mName")); 
    mProduct.setPrice(jsonArray.getJSONObject(i).getDouble("mPrice")); 
    mProducts.add(mProduct); 

    System.out.println(mProducts.get(i)); // shows you what you want, because you are in the loop 
} 

for(Product product: mProducts){ 
    System.out.println(product); // shows, what is realy in the ArrayList. it is always last value 
} 

你需要的是

for(int i = 0; i<jsonArray.length(); i++){ 
    Product product = new Product(); 
    product.setId(jsonArray.getJSONObject(i).getInt("mId")); 
    product.setName(jsonArray.getJSONObject(i).getString("mName")); 
    product.setPrice(jsonArray.getJSONObject(i).getDouble("mPrice")); 
    mProducts.add(product); 

    System.out.println(mProducts.get(i)); 
} 

for(Product product: mProducts){ 
    System.out.println(product); // now you have all values 
} 
+0

是的,它現在的工作。 –