I have a content provider that returns a MatrixCursor for the query() method.
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;
}
In the LoaderManager's onLoadFinished() callback method I use the cursor data to update a text view.
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);
}
The question now is, how do I add a new row to the MatrixCursor that will notify the change to LoaderManager's callback methods promptly?
I hope, I have made the question clear. Thanks in advance.
I hope it's not too late or may be someone else could help.
The tricky thing here. It's you have to make a new cursor every time you query to the contentProvider for this reason I have my item list and every time I query content provider I build a new cursor with my backed item list that have new items.
Why I have to do tha? Otherwise you are going to get an exception becouse CursorLoader attempt to register an observer inside a cursor that already have one. Notice that the way to build new rows in a CursorMatrix is permitted in api level 19 and above, but you have alternative ways but involve more borring code.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With