[英]Listview displaying only last item in each row?
我正在從php Server檢索對象的JSON Array並將其顯示在ListView上,我能夠成功檢索數據並將其存儲到Arraylist中,但是當我嘗試在ListView上顯示它時,只有最后一個項目顯示多次。 我正在使用Volley回調接口存儲數據,並使用ListFragment。 這是我的代碼:
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;
}
您僅創建了一個Product mProduct
實例
每個設置員將覆蓋先前的值
在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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.