android - 具有非数据库内容提供者的 Matrixcursor

标签 android android-contentprovider android-loadermanager matrixcursor

我有一个内容提供程序,它为 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() 回调方法中,我使用光标数据更新 TextView 。

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 回调方法的变化?

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

最佳答案

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

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

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

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

关于android - 具有非数据库内容提供者的 Matrixcursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22264711/

相关文章:

android - 创建 ListPreference 选项菜单

java - Android Toast 抛出错误

android - 基于 SQLite 支持的 ContentProvider 更新 ListView

带复选框的 Android 可过滤回收 View

android - 使用ActionBarSherlock时ActionBar下的阴影

android - 在 onReceive() 监听之前注销广播调用

android - eclipse 中 android sdk 中的内容提供程序

android - 我是否需要使用从我的 insert() 方法返回的相同 URI 来获取一行

android - 以菊花链方式连接 Android Loader 是个坏主意吗?

android - LoaderManager.restartLoader() 是否总是会导致调用 onCreateLoader()?