gpt4 book ai didi

java - 回调监听器无法正常工作

转载 作者:行者123 更新时间:2023-12-02 02:46:54 26 4
gpt4 key购买 nike

我正在使用Realm library对于我的应用程序。我做了一个异步请求来获取这样的对象:

    public static void getMissions(final List<StatutMission> listStatus, final SListener<List<RMission>> listener) {

final String[] statesCode = new String[listStatus.size()];

for (int i = 0; i < listStatus.size(); i++) {
statesCode[i] = listStatus.get(i).getStateCode();
}


final RealmResults<RMission> results = Realm.getDefaultInstance().where(RMission.class).in("state", statesCode).findAllAsync();
results.addChangeListener(new RealmChangeListener<RealmResults<RMission>>() {
@Override
public void onChange(RealmResults<RMission> element) {

Log.d(TAG, element.size() + " mission(s) found in database with states " + StringUtils.arrayToString(statesCode, ","));
listener.onResponse(Realm.getDefaultInstance().copyFromRealm(element));
results.removeChangeListener(this);

}
});

}

监听器类:

public interface SListener<T> {

void onResponse(@Nullable T result);

}

我在多个设备中测试了我的代码,但仅在一台设备(三星平板电脑)上出现了问题。

问题代码:

   MissionManager.getMissions(listStatus, new SListener<List<RMission>>() {
@Override
public void onResponse(List<RMission> result) {

谁能帮我解决这个问题吗?

提前致谢。

最佳答案

1.) Realm.getDefaultInstance().where(...Realm.getDefaultInstance().copyFromRealm(...) 您正在打开 Realm 实例将永远无法关闭,请阅读 the docs

2.) 您没有将 RealmResults 保留为字段引用,因此终结器将在评估异步查询之前销毁它,因此不会调用回调,请阅读文档 herehere

From javadoc:

Registering a change listener will not prevent the underlying RealmResults from being garbage collected. If the RealmResults is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

public class MyActivity extends Activity {

private RealmResults<Person> results; // Strong reference to keep listeners alive

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
results = realm.where(Person.class).findAllAsync();
results.addChangeListener(new RealmChangeListener<RealmResults<Person>>() {
@Override
public void onChange(RealmResults<Person> persons) {
// React to change
}
});
}
// remove change listeners, and close Realm in onDestroy()
}

3.) 如果您在 UI 线程上急切地复制惰性求值 RealmResults 中的每个惰性求值元素,那么异步求值查询的所有麻烦都毫无意义,所以你应该重新评估你的逻辑,特别是在你读完the relevant docs on how Realm queries work之后.

All fetches (including queries) are lazy in Realm, and the data is never copied.

由于数据永远不会被复制,因此您没有理由使用 copyFromRealm()

关于java - 回调监听器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com