SQLite查询后填充ListView

时间:2018-02-20 06:07:22

标签: android xml listview arraylist

我需要填充查询中的数据,并使用自定义ListViewItem上填充该数据。

OnCreateView,我正在调用我的适配器:

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
                (getContext(), android.R.layout.simple_list_item_1, stops)

这是我的LoadData

的完整代码
public void LoadData() {
    String query = "SELECT ticket_placeto, COUNT(CASE WHEN passenger_type <> 'Baggage' THEN 1 END) AS Pass,\n" +
            "COUNT(CASE WHEN passenger_type =  'Baggage' THEN 1 END) AS Baggage FROM tickets GROUP BY ticket_placeto";

    c = sqldb.rawQuery(query, null);

    if (c != null) {
        if (c.moveToFirst()) {
            do {
                String placeto = c.getString(0);
                String passengers = c.getString(1);
                String baggages = c.getString(2);

                stops.add(placeto + "                 " + passengers + "               " + baggages);

            } while (c.moveToNext());
        }
    }
}

这是它的输出

我刚刚对stops.add上的空格进行了硬编码,以暂时显示数据。我已经有一个自定义ListItem Layout但是没有同时使用它。

这是chrome://inspect

上查询的结果

enter image description here

2 个答案:

答案 0 :(得分:1)

供您参考,我只需重新编码LoadData。感谢 pskink 在这里帮助我以及在这个帖子上做出回应的其他人。

  public void LoadData() {
    String query = "SELECT _id, ticket_placeto, " +
            "COUNT(CASE WHEN passenger_type <> 'Baggage' THEN 1 END) AS Pass," +
            "COUNT(CASE WHEN passenger_type =  'Baggage' THEN 1 END) AS Baggage " +
            "FROM tickets GROUP BY ticket_placeto";


    final String[] columns = new String[]{
            DBHelper.TICKET_ID,
            DBHelper.TICKET_PLACETO,
            "Pass",
            "Baggage",
    };

    final int[] to = new int[]{
            R.id.stops_id,
            R.id.stops_location,
            R.id.stops_passengers,
            R.id.stops_baggages
    };


    c = sqldb.rawQuery(query,null);
    if (c != null) {
        adapter = new SimpleCursorAdapter(getContext(), R.layout.item_for_stops, c, columns, to, 0);
        lv_stops.setAdapter(adapter);
    }
}

答案 1 :(得分:0)

1.首先在activty的onCreate()方法中初始化List,

cv2.putText(img, str(sampleNum + 1), (x,y+h+30), font, 2, 255)

然后将其传递给ArrayAdapter。

2.成功执行查询后,将数据添加到“停止”列表中,然后 在代码中添加以下行。

ArrayList<String> stops = new ArrayList<>();