MicroR MicroR - 26 days ago 16
Android Question

RealmChangeListener onChange() never fires

Realm Version:

2.1.1


I have a fragment and in it's
onCreate()
I register a
RealmChangeListener
. However, when my object is updated, the
RealmChangeListener
's
onChange()
never fires.

Actually, that is a lie, for some strange reason if I clean install my app it will work a few times before not working at all for all until I uninstall/reinstall the app again.

I know for a fact my
Realm
operations are writing to
Realm
because if I restart my app, the UI definitely displays those new changes. No idea why maybe the listeners would unregister?

Feeling a little confused here, I hope I am not doing something wrong:

public class ProfileFragment extends Fragment {

private Realm mRealm;
private RealmChangeListener mRealmChangeListener;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mRealm = Realm.getDefaultInstance();

// Get user from Realm
RealmQuery<User> query = mRealm.where(User.class);
User user = query.findFirst();

updateUI(user);

mRealmChangeListener = new RealmChangeListener<User>() {
@Override
public void onChange(User user) {
updateUI(user);
}
};

user.addChangeListener(mRealmChangeListener);

}

// Todo:
// Unregister listeners + realm in OnDestroy();
}

Answer

Your problem could be that you don't actually retain a strong reference to your User object.

public class ProfileFragment extends Fragment {

    private Realm mRealm;
    private RealmChangeListener mRealmChangeListener;
    private User user;

...

            // Get user from Realm
            RealmQuery<User> query = mRealm.where(User.class);
            user = query.findFirst();

Also, you're in a fragment, so you should consider moving the onCreate()/onDestroy() to onCreateView() and onDestroyView() (unless this is a retained fragment, in which case go ahead).

If the problem persists, report back here.

Comments