我已经设置了一个片段,以使用CursorLoader从自定义内容提供程序中提取数据。
问题是,当我使用内容解析器更新SQLite表中的记录时,光标不会刷新,即getContext().getContentResolver().notifyChange(myUri, null)
没有效果。我必须退出片段,然后再次打开以查看更改。
我认为问题在于加载程序未观察到我用于更新行的URI:
content://com.myapp.provider/MyTable/Set/22
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;
}
解决方案是调用notifyChange()
正在观察的Uri,即集合,而不是行。
为此,我们需要进行一些更改:
调用更新时,将设置ID包括在URI中:
mContext.getContentResolver().update("content://com.myapp.provider/MyTable/Set/22/167", values, null, null);
将单行的URI模式从“ /#”更改为“ / Set /#/#”
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 + "/Set/#/#", URITYPE_SINGLE_ROW);
}
然后在更新功能中,构造一个必须通知的新Uri:
List<String> pathSegments = uri.getPathSegments();
String mySetID = pathSegments.get(2);
Uri mySetUri = Uri.parse("content://" + AUTHORITY + "/" + TABLE_PATH + "/Set/" + mySetID);
getContext().getContentResolver().notifyChange(mySetUri, null);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句