2017-02-12 52 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

是的,它现在的工作。 –