内容解析器notifyChange()无法正常工作

fai*_*zal 2 android android-contentprovider

我已经设置了一个片段,使用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;
}
Run Code Online (Sandbox Code Playgroud)

按钮点击片段:

mContext.getContentResolver().update("content://com.myapp.provider/MyTable/167", values, null, null);
Run Code Online (Sandbox Code Playgroud)

内容提供者类:

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;
}
Run Code Online (Sandbox Code Playgroud)

ban*_*ing 5

我有一个类似的问题,在这里找到了解决方案.

简而言之,事实证明我需要调用我的内容提供者setNotificationUri(ContentResolver cr, Uri uri)query()方法返回的游标.