首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >非数据库内容提供程序的Matrixcursor

非数据库内容提供程序的Matrixcursor
EN

Stack Overflow用户
提问于 2014-03-08 11:40:31
回答 1查看 2K关注 0票数 6

我有一个内容提供者,它为MatrixCursor ()方法返回一个查询。

代码语言:javascript
复制
Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
   MatrixCursor cursor = new MatrixCursor(new String[]{"a","b"});
   cursor.addRow(new Object[]{"a1","b1"});
   return cursor;
}

在LoaderManager的onLoadFinished()回调方法中,我使用光标数据来更新文本视图。

代码语言:javascript
复制
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    cursor.moveToFirst();
    String text = (String) textView.getText();
    while (!cursor.isAfterLast()) {
        text += cursor.getString(1);
        cursor.moveToNext();
    }
    textView.setText(text);

}

现在的问题是,如何向MatrixCursor添加新行,以便及时通知LoaderManager的回调方法的更改?

我希望,我已经把问题说清楚了。提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2015-03-19 23:52:29

我希望现在还不算太晚,或许其他人能帮上忙。

这里最棘手的是。每次你查询contentProvider的时候,你必须创建一个新的游标,因为这个原因,我有我的项目列表,并且每次我查询内容提供者时,我都会用我支持的包含新项目的项目列表构建一个新的游标。

为什么我要这么做?否则,您将得到一个异常,因为CursorLoader试图在已经有一个观察者的游标中注册一个观察者。请注意,在CursorMatrix中构建新行的方法在API19级和更高版本中是允许的,但是您有其他方法,但涉及更多的借用代码。

代码语言:javascript
复制
public class MyContentProvider extends ContentProvider {

List<Item> items = new ArrayList<Item>();

@Override
public boolean onCreate() {
    // initial list of items
    items.add(new Item("Coffe", 3f));
    items.add(new Item("Coffe Latte", 3.5f));
    items.add(new Item("Macchiato", 4f));
    items.add(new Item("Frapuccion", 4.25f));
    items.add(new Item("Te", 3f));

    return true;
}


 @Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {

    MatrixCursor cursor = new MatrixCursor(new String[] { "name", "price"});

    for (Item item : items) {
        RowBuilder builder = cursor.newRow();
        builder.add("name", item.name);
        builder.add("price", item.price);
    }

    cursor.setNotificationUri(getContext().getContentResolver(),uri);

    return cursor;
}


@Override
public Uri insert(Uri uri, ContentValues values) {
    items.add(new Item(values.getAsString("name"),values.getAsFloat("price")))

    //THE MAGIC COMES HERE !!!! when notify change and its observers registred make a requery so they are going to call query on the content provider and now we are going to get a new Cursor with the new item

    getContext().getContentResolver().notifyChange(uri, null);

    return uri;
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22264711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档