Issue
In the above code, realm can't execute its transaction inside the new Thread, no errors are displayed, but its not executed either.
I have already tried to put the transaction outside of the thread, the problem is that it consumes the UI thread, but it works perfectly, and i want to display a smooth loading to the user while Retrofit and Realm do their work
threadNova = new Thread() {
@Override
public void run() {
super.run();
try {
Response<Retorno> response = getCall.execute();
final Retorno responsebody = response.body();
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(realm1 -> {
//Save things on bank
// No errors but don't enter here either
});
} catch (IOException e) {
e.printStackTrace();
}
}
};
Solution
You need to call Realm.close()
.
You using Java Thread without looper it means that your Realm not refreshed until you call Realm.close()
, so close your Realm inside finally block.
try(Realm realm = Realm.getDefaultInstance()) {
Response<Retorno> response = getCall.execute();
final Retorno responsebody = response.body();
realm.executeTransaction(realm1 -> {
//Save
});
} catch (IOException e) {
e.printStackTrace();
}
}
From docs:
If you obtain a Realm instance from a thread associated with a Looper, the Realm instance comes with an auto-refresh feature. (Android’s UI thread is a Looper.) This means the Realm instance will be periodically updated to the latest version. This lets you keep your UI constantly updated with the latest content with almost no effort!
If you get a Realm instance from a thread that does not have a Looper attached, objects from that instance won’t be updated until you call the waitForChange method. Holding on to an old version of your data is expensive in terms of memory and disk space, and the cost increases with the number of versions between the one being retained and the latest. This is why it is important to close the Realm instance as soon as you are done with it in the thread.
If you want to check whether your Realm instance has auto-refresh activated or not, use the isAutoRefresh method. soon as you are done with it in the thread.
Answered By - Pavel Poley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.