【问题标题】:Matrixcursor with non-db content provider具有非数据库内容提供者的 Matrixcursor
【发布时间】:2014-03-08 03:40:31
【问题描述】:

我有一个内容提供程序,它为 query() 方法返回一个 MatrixCursor。

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() 回调方法中,我使用光标数据更新文本视图。

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 的回调方法的更改?

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

【问题讨论】:

    标签: android android-contentprovider android-loadermanager matrixcursor


    【解决方案1】:

    我希望现在还不算太晚,或者其他人可以提供帮助。

    这里很棘手。每次查询 contentProvider 时,您都必须创建一个新游标,因此我有我的项目列表,每次查询内容提供者时,我都会使用包含新项目的支持项目列表构建一个新游标。

    为什么我必须这样做?否则你会得到一个异常,因为 CursorLoader 试图在已经有一个的游标内注册一个观察者。 请注意,在 api 级别 19 及更高版本中允许在 CursorMatrix 中构建新行的方式,但您有其他方式,但涉及更多无聊的代码。

    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;
    }
    

    【讨论】:

    • 如果我们想使用选择子句只更新一列而保持其他列不变,那么更新和删除方法将如何工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 2012-07-29
    相关资源
    最近更新 更多