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.

Gus
  • 942
  • 9
  • 32

1 Answers1

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]));
        }
    }
Nick Titov
  • 588
  • 5
  • 19
  • 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 ? – Gus Dec 25 '16 at 11:54
  • If you will use SyncAdapter it has to have ContentProvider. But you can use just dummy ContentProvider as mentioned here: http://stackoverflow.com/questions/4649808/syncadapter-without-a-contentprovider – Nick Titov Dec 26 '16 at 10:11
  • 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. – Gus Dec 27 '16 at 07:15