Andy Strife Andy Strife - 5 months ago 53
JSON Question

Json from Retrofit to SQLite Database

Just wondering how you would send Json Data from Retrofit to a SQLite Database (via a ContentProvider)?

Before Retrofit, I used to do my Request, get the Json and send it to the ContentProvider in an IntentService. So the Calls to the Server and then write to the Database are done in a worker Thread.

But starting to use Retrofit 2 now; got my Json; I'm wondering how to write it to the Database?
I would serialize the POJO, send it to an IntentService using an Intent and do the write to the DB in onHandleIntent(Intent).

But I'm wondering if this is the right way and if there isn't another standard way?

I have searched around but nothing talked about it.

Thanks

Answer

The SyncAdapter is a pretty standard way to solve this problem. It encapsulates data transfer between your server and your local database. As a warning, there's quite a bit of setup involved.

If you don't want to write a SyncAdapter, your proposed approach works fine. I would probably recommend making the retrofit call in your IntentService. This way you don't have to parcel all of that json in your Intent. For example:

// In IntentService
@Override public void onHandleIntent(Intent intent) {
    MyModel data = getRetrofitCall().execute()
    // convert data to ContentValues
    getContentResolver().bulkInsert(contentValues)
}

Then, in your Activity, or anywhere you need to trigger a sync, you just start up the IntentService.

Comments