如何获取唯一列值并从游标获取第一个条目和最后一个条目

时间:2016-10-28 01:55:08

标签: android sqlite listview

我有以下Sqlite表:

Name            Date
Challen         2016-03-04
Challen         2016-03-12
Challen         2016-05-14
Challen         2016-02-20
Testing         2016-07-14
Testing         2016-08-22
Testing         2016-07-29
Testing         2016-09-12

我有一个获取这些数据的类,在我的活动中,我正在使用Cusor重新获取这些数据:

Cursor crs = MyDBHelper.GetTheData(); // retrieves all the rows above
PopulateLV pgv = new PopulateLV(getActivity(), crs);
...
public class PopulateLV extends CursorAdapter {
    public PopulateLV(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.disp_data_in_grid, parent, false);
    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        //question...
    }
}

ListView单项模板:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name" />

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/start" />

    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/end" />
</LinearLayout>

我期待的是:

  • 从表格中获取唯一的Name列,并在列表视图中填充文本视图
  • 从上面的唯一名称(由Date排序)获取第一个Date条目(这是第一行)和最后一个Date条目(这是最后一个< / LI>

结束ListView应如下所示:

Challen
Start: 2016-02-20
End: 2016-05-14
-----------------------------------------
Testing
Start: 2016-07-14
End: 2016-09-12
-----------------------------------------

1 个答案:

答案 0 :(得分:1)

为什么要将所有数据检索到cursor?从您的问题来看,您似乎不需要从数据库加载所有内容,然后对其进行过滤。相反,你应该只编写一个有意义的SQL查询,只检索你需要的东西。

SELECT name, MIN(date) AS start, MAX(date) AS end
FROM some_table
GROUP BY name

这给了我以下结果:

name        start           end

Challen     2016-02-20      2016-05-14
Testing     2016-07-14      2016-09-12