这个问题是问题 Content Resolver vs Cursor Loader 的后续问题。 答案清楚地说明了如何使用 Content Resolver 将记录插入 sqlite Db 中。我的问题如下:
- 我可以使用加载器(普通加载器)来实现此功能吗?
例如:
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
switch (id) {
case AppConstants.LOADER_ADD_FAV_PHONE_NUM:
ContentValues values = new ContentValues();
values.put(DBHelper.TM_DB_COLUMN_PHONE_NUMBER,
directionOrder);
values.put(TransitMeDBHelper.TM_DB_COLUMN_NAME_ID, selectionArgs[0]);
Uri insertFavStop =getContentResolver().insert(TransitMeContentProvider.CONTENT_URI_INSERT_FAV_PHONE,
values);
break;
}
return null;
}
这会在主 UI 线程还是工作线程中运行该功能。据我了解,我不会收到此回调,因为内容解析器将返回 URI,而不是包含数据的游标。
我尝试运行这段代码,但它的行为有点奇怪..记录了重复的插入并且不一致,有人可以向我展示一些使用加载器执行插入操作的正确资源吗(我已经看到了很多带有查询示例的示例它就像一个魅力:))
感谢您的宝贵时间。
最佳答案
Can i use a loader(Normal Loader) to implement this functionality ?
您无法使用默认的 CursorLoader
插入数据。如果您实现自己的Loader
,您可能可以使用loadInBackground
方法来执行插入,但这最多只会让您的代码变得尴尬(而且我不知道是否真的有效)。
Would this run the functionality in the Main UI thread or a worker Thread . I understand that i would not receive callbacks for this as the content resolver will return a URI instead of the cursor containing data .
加载器回调将在实现它们的线程上运行(最有可能是 UI 主线程),因此您可以在主 UI 线程上执行 getContentResolver().insert()
阻塞主 UI 线程的可能性。
I tried running this code but it behaves kind of wierd .. Duplicate inserts are recorded and its not consistient ,
您测试过onCreateLoader
方法被调用了多少次吗?
Could someone show me to some right resource which uses a Loader to do Insert operations ( I have seen many examples with query examples and it works like a charm :) )
不要使用/尝试使用Loader
在ContentProvider
/Database中插入数据。它对于查询来说就像一个魅力,因为加载器被设计为从数据源加载数据(而不是插入数据),这就是它们的目的。如果您想插入数据,请使用 AsyncTask
(另请参阅 AsyncQueryhandler
),这是一个常规线程。
关于android - 在android中通过Loaders插入记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13571805/