I am having an issue where Realm sometimes returns me different data every time I do the same query. Currently I am using an SyncAdapter for uploading. The idea is that we are trying to implement offline mode.
So when the User creates an item it get's added to Realm db. I am generating the ID for that item manually by getting the maxId and adding 1000 to it. After that I am sending the itemID to the UploadSyncAdapter where I get the itemById and send it to the backend and the backend returns me the item with the real ID. So after that I delete the old item and just insert the new item into Realm.
After I go back and read the data it returns every second time for example an array of size 115 data and the other time an array of size 116. I even search for the item with the debugger by ID and it really once finds the item, the second time it doesn't. But it looks like after I rebuild the project the item is there and it works normally, or if I rerun the app by using Instant Run.
Any help appreciated...
UPDATE Btw I am using RXjava to get the data from the server but it is being subscribed and observed on the current thread (SyncAdapter thread).
Here's the code:
@Override
public void onNext(TaskResponse taskResponse) {
tasksDatabaseManager.deleteTaskById(taskId);
List<Task> tasks = taskResponse.getTaskDataList();
tasksDatabaseManager.insertTasks(tasks);
}
public void deleteTaskById(int taskId){
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmResults<Task> rows = realm.where(Task.class).equalTo(ID, taskId).findAll();
rows.deleteAllFromRealm();
realm.commitTransaction();
realm.close();
}
private void copyOrUpdateTasks(List<Task> tasksList){
Realm realm = Realm.getDefaultInstance();
ArrayList<Task> updatedTaskList;
//first initialize task permissions
updatedTaskList = filterTasksByPermission(tasksList);
//initialize custom task data
for (Task task : updatedTaskList) {
initializeTaskCustomFields(task);
}
//save new data
Log.d(TAG, "tasks number before update: " + getTasks().size());
realm.beginTransaction();
realm.copyToRealmOrUpdate(updatedTaskList);
realm.commitTransaction();
realm.close();
Log.d(TAG, "tasks number after update: " + getTasks().size());
}
In the filterTasksByPermission I just calculate some permissions for the tasks, but the task is being returned in the list. And in the initializeTaskCustomFields I am also just calculating 2 fields of the object before saving to Realm (so that I have those values also saved in Realm)