sai
sai

Reputation: 107

realm not fetching data

I have problem working with realm.

findAll and findAllAsync doesnot return any data from realm.

I am updating realm object from main thread like this.

public void updatePhoto(final int ticketID) {
    realm.beginTransaction();
    RealmResults ticketPhotos =  realm.where(TicketPhoto.class).equalTo("TicketID", ticketID).findAll();`           
    for (TicketPhoto ticketPhoto : ticketPhotos) { 
        ticketPhoto.IsModified = true;
    }
    realm.commitTransaction(); 
} '$'

At same time one background service is running for every five minutes and keeps checking for any objects having IsModified flag as true. From my background service(IntentService), am using AsyncTask and in doInBackground, am trying to get those IsModified records and I assume realm should pick those records and update with my server. Used the below code to get data from realm.

public RealmResults getTicketPhotosToSave (){
    return realm.where(TicketPhoto.class)
           .equalTo("IsModified", true)
           .findAll(); 
}

When am still in the same Photo activity where I save photo to realm with IsModified flag as true, realm in background service is not picking those records. But when I destroy the app and just run it again, service is now picking those records. Am not sure if am doing something wrong here.

Upvotes: 2

Views: 1709

Answers (2)

sai
sai

Reputation: 107

Its working. thanks for your support

Now I understood that unless we are updating the data on same thread, no need to close realm. We need to close realm always when we need access to those changes in different thread . Since background thread always needs access to all objects, we have to close and open realm just before accessing data.

So before accessing/querying data, I am refreshing realm as @Zhuinden suggested ( realm not fetching data) and then realm.Close(). After this I am creating instance (realm = Realm.getDefaultInstance(); )

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81539

I really hate recommending this solution, but you should force a refresh with the package-internal methods after Realm.getInstance() on your IntentService's Realm instance. This current solution I provide works for v1.2.0. Use it only on background threads (primarily your periodically running method).

package io.realm; // <---- this is important 

public class RealmRefresh {
    public static void refreshRealm(Realm realm) {
        Message message = Message.obtain();
        msg.what = HandlerControllerConstants.LOCAL_COMMIT;
        realm.handlerController.handleMessage(msg);
    }
}

And then call

try {
    mRealm = Realm.getDefaultInstance();
    RealmRefresh.refreshRealm(mRealm);
    // do things
} finally {
    if(mRealm != null) {
        mRealm.close();
    }
}

Upvotes: 0

Related Questions