假设异步API调用返回成员数据,这是一个RealmObject,而成员则保存到领域。
public class Member extends RealmObject {
String name;
}
现在我想将RealmObjectChangeListener添加到成员对象(比如成员),以便我们可以在数据可用时更新UI。但是,首先,成员表为空,成员为空,因为API调用(用于获取成员数据)是异步的。将RealmObjectChangeListener添加到成员将导致NullPointerException。如何处理这种情况?
答案 0 :(得分:2)
如果您正在倾听所有成员的意见,那么这很简单:保持对成员的字段引用(在RecyclerView的ViewHolder中很容易)并将RealmObjectChangeListener添加到从results.get()
获取的成员中,绑定到ViewHolder。
void bind(Member member) {
if(this.member != null) {
this.member.removeAllChangeListeners();
}
this.member = member;
this.member.addChangeListener(...);
假设您正在等待具有特定member
的特定name
,并且您只关心该成员:
private final Handler handler = new Handler(Looper.getMainLooper());
private RealmResults<Member> objectResults;
private RealmChangeListener<RealmResults<Member>> objectTracker = (results) -> {
if(member != null && member.isValid()) {
return;
}
if(realm.isInTransaction()) {
handler.post(() -> {
setupMember(results);
});
} else {
setupMember(results);
}
};
private void setupMember(RealmResults<Member> members) {
if(member != null && member.isValid()) {
member.removeAllChangeListeners();
}
member = members.first(null);
if(member != null) {
member.addChangeListener((member, fieldChangeSet) -> {
// do whatever
});
}
}
private Member member;
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
realm = Realm.getDefaultInstance();
objectResults = realm.where(Member.class).equalTo("name", name).findAllAsync();
objectResults.addChangeListener(objectTracker);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(member != null) {
member.removeAllChangeListeners();
}
objectResults.removeAllChangeListeners();
realm.close();
}
编辑:如果您不需要字段级更改:
private RealmResults<Member> objectResults;
private RealmChangeListener<RealmResults<Member>> objectTracker = (results) -> {
setupMember(results);
};
private void setupMember(RealmResults<Member> members) {
Member member = members.first(null);
if(member != null) {
updateViews(member); // update views with member
} else {
// member doesn't exist or was deleted
}
}
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
realm = Realm.getDefaultInstance();
objectResults = realm.where(Member.class).equalTo("name", name).findAllAsync();
objectResults.addChangeListener(objectTracker);
}
@Override
protected void onDestroy() {
super.onDestroy();
objectResults.removeAllChangeListeners();
realm.close();
}