我已经设置了一个片段,使用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内,所以它应该重置光标?
下面是代码,以防更清晰:
在片段中创建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;
}
最佳答案
我也有类似的问题,发现了solution here。
简而言之,我需要在内容提供者的setNotificationUri(ContentResolver cr, Uri uri)
方法返回的游标上调用query()
。