我正在尝试构建一个Android应用程序,该应用程序向JSON API发出http请求,以便创建并填充本地SQLite数据库,同时通过内容提供程序公开该数据库。
背景: 我刚刚开始学习android所以我首先让它在没有内容提供者的情况下使用AsyncTaskLoader的自定义版本,我在那里执行异步请求并直接写入数据库。
当我试图让它与内容提供程序一起工作时,我试图摆脱CustomAsyncTaskLoader,因此我可以使用CursorLoader。 我在内容提供程序的onCreate()方法中将初始http请求作为异步任务,但经过几个小时的查找问题后,似乎必须从主UI线程或onPostExecute()调用异步任务方法不会被调用。
所有这些时间都在寻找答案,这让我想到必须有更好的方法来做到这一点......
我提前感谢所有的帮助。
答案 0 :(得分:0)
您缺少的组件是Sync Adapter - 它们用于从内部服务(例如Web服务器)传输数据并将其插入到Content Provider中。它们还提供了在集中Account Authenticator中构建用户帐户和处理身份验证的功能(如果您不需要该功能,您当然可以构建stub Authenticator。)
一旦构建了身份验证器/内容提供商/同步适配器,您就可以通过编程方式create an account(即使它只是名称的“后台同步”),然后run the sync adapter加载您的Content Provider包含数据。对于第一次运行,您可能希望run it on demand:
Account account; // Account created by your application
String AUTHORITY; // AUTHORITY associated with your Content Provider
Bundle settingsBundle = new Bundle();
// Set the flags to make it run right now
settingsBundle.putBoolean(
ContentResolver.SYNC_EXTRAS_MANUAL, true);
settingsBundle.putBoolean(
ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
// Request the sync, causing the Sync Adapter's onPerformSync to be called
ContentResolver.requestSync(account, AUTHORITY, settingsBundle);