【发布时间】:2012-06-15 13:26:23
【问题描述】:
我正在构建一个应用程序,它遵循IOSched 检索数据的方式,但我认为我会使用CursorLoader 而不是ContentObserver:
我也一直在参考 Reto 的android-protips-location,它确实使用了CursorLoader,并且逻辑流程与 IOSched 非常相似,因此:
initLoader → startService (serviceIntent) → handleIntent → insert into DB → notifyChange → onLoadFinished → update UI
我期望看到的是 CursorLoader 在数据库上执行 insert 后返回 Cursor。
目前,片段onActivityCreated 调用initLoader 并在ContentProvider 上运行查询,这将返回该时间点的Cursor 以及当前数据。
但是,当我执行刷新时,似乎没有触发onLoadFinished。日志显示ContentProvider上的delete和insert被执行,但查看日志显示notifyChange在insert时被调度。
// in my Fragment:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
refreshWelcome();
}
public void refreshWelcome() {
Intent i = new Intent(getActivity(), SyncService.class);
i.setAction(SyncService.GET_WELCOME);
getActivity().startService(i);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri queryUri = AppContract.Welcome.CONTENT_URI;
String[] projection = new String[] { Welcome.WELCOME_FIRST_NAME };
String where = null;
String[] whereArgs = null;
String sortOrder = null;
// create new cursor loader
CursorLoader loader = new CursorLoader(getActivity(), queryUri, projection, where, whereArgs, sortOrder);
return loader;
}
//in AppProvider (which extends ContentProvider)
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case WELCOME: {
long rowId = db.insertOrThrow(Tables.WELCOME, null, values);
if (rowId > 0) {
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
}
}
return null;
}
【问题讨论】:
-
是否有理由在 IntentService 中使用 CursorLoader? IntentService 是一个在单独线程中执行工作的队列。为什么不直接执行查询?
标签: android android-intent android-contentprovider android-cursorloader