我已经设置了一个片段来使用 CursorLoader 从自定义内容提供程序中提取数据。
问题是,当我使用内容解析器更新 SQLite 表中的记录时,光标不会刷新,即getContext().getContentResolver().notifyChange(myUri, null)
没有影响。我必须退出片段并再次打开它才能看到更改。
我认为问题是加载器没有观察到我用来更新行的 URI:
- 创建加载程序的 URI -
content://com.myapp.provider/MyTable/Set/22
- 更新行的 URI -
content://com.myapp.provider/MyTable/167
167 标识表中的唯一行。 22 标识表中的一组行。有没有什么方法可以告诉加载器第 167 行属于第 22 行,因此它应该重置光标?
这是代码,以防它带来更多清晰度:
在 Fragment 中创建 CursorLoader :
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle queryBundle) {
CursorLoader cursorLoader = new CursorLoader(getActivity(), Uri.parse("content://com.myapp.provider/MyTable/Set/22"), myProjection, null, null, null);
return cursorLoader;
}
在按钮上单击片段:
mContext.getContentResolver().update("content://com.myapp.provider/MyTable/167", values, null, null);
内容提供者类:
private static final String AUTHORITY = "com.myapp.provider";
private static final String TABLE_PATH = "MyTable";
public static final String CONTENT_URI_BASEPATH = "content://" + AUTHORITY + "/" + TABLE_PATH;
private static final int URITYPE_TABLE = 1;
private static final int URITYPE_SINGLE_SET = 2;
private static final int URITYPE_SINGLE_ROW = 3;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static{
sUriMatcher.addURI(AUTHORITY, TABLE_PATH,URITYPE_TABLE);
sUriMatcher.addURI(AUTHORITY, TABLE_PATH + "/Set/#", URITYPE_SINGLE_SET);
sUriMatcher.addURI(AUTHORITY, TABLE_PATH + "/#", URITYPE_SINGLE_ROW);
}
@Override
public int update(Uri myUri, ContentValues values, String selection, String[] selectionArgs){
int rowCount = 0;
String id;
SQLiteDatabase db = localDB.getWritableDatabase();
int uriType = sUriMatcher.match(myUri);
switch(uriType){
case URITYPE_SINGLE_ROW :
id = uri.getLastPathSegment();
//selection and selectionArgs are ignored since the URI itself identifies a unique row.
rowCount = db.update(MyTable.TABLE_NAME, values, MyTable.COLUMN_ID + " = ?", new String[] {id});
}
getContext().getContentResolver().notifyChange(myUri, null);
return rowCount;
}