我有一个内容提供商,它返回了query()方法的矩阵cursor。
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的OnloadFined()回调方法中,我使用光标数据更新文本视图。
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);
}
现在的问题是,如何在矩阵cursor中添加新行,该行会及时通知LoaderManager的回调方法的更改?
我希望,我已经明确了这个问题。预先感谢。
我希望还为时不晚,或者可能是别人可以帮助的。
这里棘手的事情。由于我有我的项目列表,每当您查询ContentProvider时,您都必须制作一个新的光标。
为什么我必须做?否则,您将获得异常,因为光标加载程序会尝试在已有一个的光标内注册一个观察者。请注意,在Cursormatrix中构建新行的方法是在API级别19及更高版本中允许的,但是您有其他方法,但涉及更多的Borring代码。
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;
}