【问题标题】:Merging data from cursor before presenting it in ListView在将光标显示在 ListView 之前合并来自光标的数据
【发布时间】:2013-12-02 19:26:38
【问题描述】:

我正在开发一个应用程序,但目前卡住了。我要做的是在 UI 上显示之前处理来自 DB 的数据。

我的应用像这样收集数据并存储在数据库中。

+--------------------+
|姓名 Used_time(s) |
+--------------------+
| C 10 |
| 12 |
| 23 |
| C 11 |
| 14 |
+--------------------+

我以基本方式实现了 CursorLoader 和自定义 CursorAdapter,它正确显示了我的原始数据库数据及其更新!对我有好处!

但我想做的是像这样在列表视图中显示应用程序的聚合时间。

+--------------------+
|姓名 Used_time(s) |
+--------------------+
| C 21 |
| 12 |
| 37 |
+--------------------+

我试图修改我的光标适配器以在适配器中进行求和,但它会自动获取每个光标的光标位置,并返回列表视图该位置的视图,无论我是否触摸 Used_time 数据。我找不到解决方法。

活动类中我当前的加载器代码..

private void loadDB() {
    getLoaderManager().initLoader(0, null, this);   
    cursorAdapter = new MyCursorAdapter(this, null);
    setListAdapter(cursorAdapter);
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = MyTable.MY_COLUMNS ;
    CursorLoader cursorLoader= new CursorLoader(this, MyContentProvider.CONTENT_URI_APPS, projection, null, null, null);
    return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    cursorAdapter.swapCursor(cursor);
}

适配器代码。

public MyCursorAdapter(Context context, Cursor cursor) {
    super(context, cursor);
        LayoutInflater inflater = LayoutInflater.from(context);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(R.layout.app_row, parent, false);
}

@Override
public void bindView (View view, Context context, Cursor cursor) {
    TextView NameTv = (TextView)view.findViewById(R.id.name);
    TextView TimeTv = (TextView)view.findViewById(R.id.time);

    String Name = cursor.getString(1);
    appNameTv.setText(Name);

    int Time = (int)(cursor.getLong(2));
    TimeTv.setText(String.valueOf(Time));           
}

我还想过创建一个新表、sharedpreference 或 hashmap 来存储聚合数据,但我认为这些都是不必要的开销,因为应用程序会不断收集数据,并且有办法通过处理适配器来解决这个问题。

有人可以提出一种有效的方法吗?提前谢谢你。

【问题讨论】:

    标签: android listview android-sqlite android-cursoradapter android-cursorloader


    【解决方案1】:

    听起来您正在寻找以下查询,但由于CursorLoader 没有为您提供执行聚合函数的选项,因此您被卡住了:

    SELECT Name, COUNT(Used_time) FROM MyTable GROUP BY Name;
    

    您应该阅读这篇关于创建自定义URIs 并可能在您的ContentProvider 中使用SQLiteQueryBuilder 的文章,以便使用CursorLoader 执行此查询

    GROUP BY with CursorLoader

    【讨论】:

    • 感谢您的精彩回答,尽管我选择采用不同的方式来做到这一点。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多