So I have created a very standard sync adapter (using this fantastic tutorial) and during onPerformSync
I run some realm transactions in a method called syncDatastore
within my DataManager
class. The issue is when the sync adapter tries to perform the sync, I get
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
Here is an excerpt from my SyncAdapter
:
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
try {
// Get the auth token for the current account
String authToken = _accountManager.blockingGetAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, true);
// run network and database operations
dataManager.syncDatastore();
} catch (Exception e) {
e.printStackTrace();
}
}
I initialize the RealmConfiguration
in my Application class with:
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfiguration);
And an example of how it is used in my DataManager
:
private Realm realm = Realm.getDefaultInstance();
public void syncDatastore() {
postResources();
pushDataToServer();
getDataFromServer();
}
private void postResources() {
ArrayList<Client> clients = new ArrayList<>();
clients.addAll(realm.where(Client.class).equalTo("isSynced", false).equalTo("apiId", "0").findAll());
Log.e("clients count", String.valueOf(clients.size()));
for (Client c : clients) {
createClientResource(c);
}
}
Please note I have tried to remove android:process=":sync"
from my service declaration in the manifest as outlined here but to no avail. I am also quite new to both SyncAdapters and Realm, so any help would be most appreciated.