How to sync data from server into android SQLite using sync adapter?

1.3k views Asked by At

1 - sync adapter was created to synchronize client and server data on the background. It is executed as a different process than the app.

2 - SQLite cannot be written by multiple processes

Considering these two points, how am I supposed to write the data parsed from server to the sqlite database ? Will a ContentProvider work in this scenario ? Is this the only option ?

ps. All answers I found here are about reading/writing from multiple threads. In this case Android implementation (using SQLiteOpenHelper) will serialize the access to a single db connection. My problem, though, is that sync adapter run as a different process than the app, making it impossible to synchronize via Java code.

1

There are 1 answers

3
Nick Titov On

ContentProvider will perfectly fit for your purpose. It will handle IPC for you. I made it in such a way:

@Override
    public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
        try {
            ResponseModel response = getAllData(deviceId);
            if (response != null) {
                addDataToDatabase(contentProviderClient, response);
            }
        } catch (RemoteException | RetrofitError exception) {
            e.printStackTrace();
        }
    }

private void addDataToDatabase(ContentProviderClient contentProviderClient, ResponseModel response) throws RemoteException {
        addTasks(contentProviderClient, response);
    }

    private void addTasks(ContentProviderClient contentProviderClient, ResponseModel response) throws RemoteException {
        if (response.getTasks() != null) {
            int size = response.tasksContentValues().size();
            contentProviderClient.bulkInsert(TaskTable.CONTENT_URI,
                    response.tasksContentValues().toArray(new ContentValues[size]));
        }
    }