سؤال

I am trying to build an android app that makes an http request to a JSON API in order to create and fill a local SQLite DB while at the same time exposing that db through a content provider.

Context : I am just starting to learn android so I first got it to work without the content provider using a custom version of an AsyncTaskLoader where I did the async requests and wrote directly to the db.

When I was trying to get it to work with a content provider I tried to get rid of the CustomAsyncTaskLoader so I could use a CursorLoader. I made the initial http request as an async task inside the onCreate() method of the content provider, but after several hours of looking for the problem it seems like if the async task must be called from the main UI thread or the onPostExecute() method doesn't get called.

All these hours looking for an answer to this lead me to guess that there must be a better way to do this...

I appreciate all the help in advance.

هل كانت مفيدة؟

المحلول

The component you are missing is a Sync Adapter - they are used to transfer data from an internal service (such as a web server) and insert it into a Content Provider. They also provide the ability to build user accounts and handle authentication in a centralized Account Authenticator (although you can certainly build a stub Authenticator if you don't need that functionality).

Once you've built your authenticator/content provider/sync adapter, you can programmatically create an account (even if it just something like 'Background Sync' for a name) and then run the sync adapter to load your Content Provider with data. For the first run, you probably want to 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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top