The title says it all. I've done some searching but haven't found anything concrete.
Do I need to call realm.close after doing realm.executeTransactionAsync or does the async transaction handle that?
Thank you
EDIT: Per EpidPandaForce, executeTransactionAsync closes the background realm instance when complete.
But what is the proper way to close the realm instance if executeTransactionAsync is called from the UI thread? In the transactions onSuccess/onFailure?
You seem like you're looking for the following scenario.
public void doWrite(MyObject obj) {
Realm realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
bgRealm.insert(obj); // assuming obj is unmanaged
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
realm.close();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
realm.close();
}
});
}
In Kotlin
fun doWrite(obj: RealmObject) {
val realm = Realm.getDefaultInstance()
realm.executeTransactionAsync({ bgRealm ->
bgRealm.insert(obj) // assuming obj is unmanaged
}, { realm.close() }, { realm.close() })
}
Related
I have this method, i want return value when the transaction complete, but i cant. This's my code
public List<Group> getConversations() {
final RealmResults<Group> conversations;
try {
mRealm = Realm.getDefaultInstance();
mRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Group> conversations = realm.where(Group.class).findAllSorted("time", Sort.DESCENDING);
cursorConversation(conversations);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
//return conversation
}
});
}
return null;
}
What should i do ?
I am not sure what are you doing in cursorConversation(..) but you can use the same method on returned values from Realm.
give a try
public List<Group> getConversations() {
try (Realm realm = Realm.getDefaultInstance()) {
return realm.copyFromRealm(realm.where(Group.class).findAllSorted("time", Sort.DESCENDING));
}
}
You don't need to run a transaction for getting the conversations. You can run your query on the realm db and add a change listener to the result. When the query completes, it'll call that change listener with the RealmResults<Converstaion>, Check this link for more.
Something like
public void listenToConversations(RealmChangeListener<RealmResults<Conversation>> listener) {
RealmResults<Conversations> conversations = realm.where(Group.class).sort("time", Sort.DESCENDING).findAllAsync();
conversations.addChangeListener(listener);
}
where listener is something like
listener = new RealmChangeListener<RealmResults<Conversations>>() {
\#Override
public void onChange(RealmResults<Conversations> conversations) {
// React to change
}
}
You'll also need to remove listener to avoid any memory leaks.
My question might be a little awkard:
My scenario:
I have a singleton which contains many references to my objects.
I initialize this singleton in my activity running an UI operation with Realm with realm.where(myobj.class).first();
In my activity I have a ViewPager with many fragments. Those fragments refers to the Singleton's properties.
In my many fragments, I need to update some of my singleton object properties, but I want to do it with an async transaction. Obv it result on a thread realm error.
Relevant code (cutted)
singleton
public class OpenedIntervention {
private static OpenedIntervention openedIntervention;
public static OpenedIntervention getIstance() {
if (openedIntervention == null) {
openedIntervention = new OpenedIntervention();
}
return openedIntervention;
}
public void dispose() {
openedIntervention = null;
}
private Intervention intervention = null;
//getter setter
}
My activity init:
//...
Intervention i = realm.where(Intervention.class).equalTo("ID", intId).findFirst(); //this realm istance has activity-scope
openedIntervention.setIntervention(i);
//...
My fragment, what I would like to do:
realm.executeTransactionAsync(
new Realm.Transaction() {
#Override
public void execute(Realm realm) {
//...
openedIntervention.getIntervention().setTIPOLOGIA_INTERVENTO(etInterventionType.getText().toString());
openedIntervention.getIntervention().setTIPOLOGIA_INTERVENTO_ID(etInterventionType.getTag().toString());
}
},
new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
//...
}
},
new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
//...
}
});
Any Idea about how can I solve this problem? I 'd like to do it async to avoid lag
I am trying to parse a local JSON file i.e. 36 mb large into realm database. I am also trying to show progress bar while doing it. But it is not showing. I then used timer to start realm task after a second, this time progress dialog starts but hangs after a second. I even tried asynch realm task but issue persists.
RealmAsyncTask transaction = realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
}
}, null);
// configuration change ...
public void onStop () {
if (transaction != null && !transaction.isCancelled()) {
transaction.cancel();
}
}
Guys, find any solution regarding this.
Use an async transaction instead
showProgressbar();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
// Import data
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
hideProgressbar();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
hideProgressbar();
}
});
I thought I was following the recommended Realm approach for running Async data inserts like this:
public void addCustomer(final Customer customer) {
Realm insertRealm = Realm.getDefaultInstance();
insertRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm backgroundRealm) {
long id = customerPrimaryKey.incrementAndGet();
customer.setId(id);
backgroundRealm.copyToRealm(customer);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.d(LOG_TAG, "Customer Added");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.d(LOG_TAG, error.getMessage());
}
});
insertRealm.close();
}
However, when I run the above code I get "Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your callback"
I am running this code in a non-Activity class, what I am doing wrong here and how can I fix it. Thanks.
Update - Fixed
It turns out that there is nothing wrong with the query, problem is that I was calling it from IntentService. I was trying to seed the database on app first run, so I fixed this like this:
protected void onHandleIntent(Intent intent) {
Realm realm = Realm.getDefaultInstance();
//Add sample Customers to database
List<Customer> customers = SampleCustomerData.getCustomers();
realm.beginTransaction();
for (Customer customer: customers){
customer.setId(customerPrimaryKey.getAndIncrement());
realm.copyToRealm(customer);
}
realm.commitTransaction();
realm.close();
}
That fixed, outside of the IntentService, the query works fine when called from a UI Thread.
In order for
insertRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm backgroundRealm) {
//...
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// !!!
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// !!!
}
});
asynchronous transaction callbacks to be called on a background thread, the thread needs to be associated with a Looper (and therefore have Handlers that can communicate with the thread with that Looper).
Solution, use synchronous transaction on background thread.
But you've already figured that out.
protected void onHandleIntent(Intent intent) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
final List<Customer> customers = SampleCustomerData.getCustomers();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
for (Customer customer: customers){
customer.setId(customerPrimaryKey.getAndIncrement());
realm.insert(customer);
}
}
});
} finally {
if(realm != null) {
realm.close();
}
}
}
Realm relies on Android' thread communication by Hanfler and Looper classes.
It looks like you query async operation from another background Thread (why?, it is already in background, use synchronous version).
To fix that you need thread with Active Looper. Use Handler thread as you background thread - it will have Looper initialized
You need to call addCustomer from UI thread.
Try this line
insertRealm.close();
to add within onSuccess and onError method. Remove it from last line as it is currently.
So your code will look like
public void addCustomer(final Customer customer) {
final Realm insertRealm = Realm.getDefaultInstance();
insertRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm backgroundRealm) {
long id = customerPrimaryKey.incrementAndGet();
customer.setId(id);
backgroundRealm.copyToRealm(customer);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.d(LOG_TAG, "Customer Added");
insertRealm.close();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.d(LOG_TAG, error.getMessage());
insertRealm.close();
}
});
}
I am trying to update records in Realm using executeTransaction function but when i call this piece of code from IntentService , onSuccess of Ream.Transaction.Callback is not getting called automatically after calling copyToRealmOrUpdate.
final Realm realm = getRealm() ;
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
//some db operations and eventually calling
realm.
realm.copyToRealmOrUpdate(employeeList);
}
}, new Realm.Transaction.Callback() {
#Override
public void onSuccess() {
// this function never gets called if
//the whole function is called from IntentService
realm.close();
}
#Override
public void onError(Exception e) {
realm.close();
}
});
private RealmConfiguration initalizeRealmConfig(){
if(realmConfiguration == null)
return realmConfiguration = new RealmConfiguration.Builder(mContext)
.name(DB_NAME)
.schemaVersion(DB_VERSION)
.build();
else return realmConfiguration;
}
public Realm getRealm(){
return Realm.getInstance(initalizeRealmConfig());
}
i am using IntentService for background db operation and webservice calls when i call above code from Activity onSuccess gets called but i really dont want to call it from Activity as per requirement.
I think reason is that you are doing a asynchronous transaction in the IntentService, and perhaps the IntentService is closed before the result is ready. An async transaction shouldn't necessary in any case since the IntentService is running on a background thread.
Just doing the below should be the same:
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
// work
}
});
realm.close();