Listview只显示每行的最后一项?

时间:2017-02-12 14:04:32

标签: java android listview android-volley

我从php Server检索JSON数组对象并在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;
}

android monitor

ListView

1 个答案:

答案 0 :(得分:3)

您只创建了一个产品mProduct

的实例

每个setter都会覆盖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
}