如何在列表视图中显示来自 mysql 的多行数据?

How do I display multiple rows of data from mysql in listview?

如何在 ListView 中显示多行数据?

现在我一次只能检索和显示一个数据(Item),我想检索多行数据(Items)并将它们全部显示在ListView中。

在本例中,我使用用户名来检索数据库中 he/she 的优惠券。所以因为我只能显示一张优惠券,我想知道如何在 ListView.

中显示多张优惠券
    protected String doInBackground(String... args) {
        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));


            JSONObject json = jsonParser.makeHttpRequest(
                    url_all_coupons, "GET", params);


            Log.d("Single Voucher Details", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {

                JSONArray productObj = json
                        .getJSONArray(TAG_COUPONS); // JSON Array


                JSONObject coupons = productObj.getJSONObject(0);

将 class 命名为任何您喜欢的名称(我们称它为 Item),此调用的每个实例将代表 Database 中的相关行(或您从中获取的任何来源信息)

Item.java may have few instance variable like coupons and userName,

public class Item {

    private String coupons;

    private String userName;

    public String getCoupons() {
        return coupons;
    }

    public void setCoupons(String coupons) {
        this.coupons = coupons;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

制作 Arraylist 类型 Item 并将此信息提供给自定义 ListView 以显示您想要的详细信息。

ArrayList<Item> list = new ArrayList<>();
        for (int i = 0; i < productObj.length(); i++) {
            Item item = new Item();
            item.setCoupons(""+productObj.getJSONObject(i).getString("CouponKey"));
            list.add(item);
        }

要填充 ListView,我建议您创建一个 List 对象(优惠券)并创建一个 Adapter 知道如何在列表中显示任意数量的优惠券。首先,您可能想为您的优惠券定义一个简单的 class(根据您的数据结构重新实现):

public class Coupon {
    private String mCouponText;

    public Coupon(String text) {
        mCouponText = text;
    }

    public String getCouponText() {
        return mCouponText;
    }
}

之后,您应该从 JSONArray 创建这些对象的列表。有不同的方法,其中之一:

List<Coupon> couponsList = new ArrayList<>();
JSONArray coupons = json
            .getJSONArray(TAG_COUPONS); // JSON Array
for (JSONObject coupon : (Iterable<JSONObject>) coupons) {
    String text = coupon.get("text");
    couponsList.add(new Coupon(text));
}

最后要做的是创建一个 Adapter 并将其设置为 ActivityListView 的适配器:

ArrayAdapter<Coupon> adapter = new ArrayAdapter<>(this, 
        android.R.layout.simple_list_item_1, couponsList);
yourListView.setAdapter(adapter);

之后 ListView 将使用 Adapter 来填充其行。您可能想要实现自己的适配器,因为它为您提供了更多选择,您将很容易找到如何操作。

更新

考虑改用 RecyclerView