1

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 Answer 1

1

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]));
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Can I use the ContentProvider only for the background process and keep using SqliteDatabase directly within the app ? Or I should use the ContentProvider internally too ?
If you will use SyncAdapter it has to have ContentProvider. But you can use just dummy ContentProvider as mentioned here: stackoverflow.com/questions/4649808/…
Thats the problem, I'm already using the SyncAdapter with dummy ContentProvider. But as the SyncAdapter is started as a different process the access to database is not synchronized, thus I get all sort of errors while using the app at the same time the batch executes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.