我在此代码中收到以下错误: "您的领域是从没有Looper的线程打开的。异步查询需要处理程序来发送查询结果"在这一行:
"RealmResults<UserVehicle> completed = realm.where(UserVehicle.class).equalTo("id", userVehicleID).findAllAsync();"
我尝试在Handler(Looper.getMain())中设置realm.executeTransaction但没有运气。我做错了什么?
PSVehicleService.getInstance(PSVehicleDetailsActivity.this).fetchVehicleTrips(userVehicle, fiveWeeksBeforeDate, lastTripDate, userID, new JsonCallback() {
@Override
public void onResponse(final JSONObject jsonObject, VolleyError error) {
if(jsonObject != null) {
Log.i("","testVehicles maybeFetchData 11");
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
try {
ObjectMapper mapper = new ObjectMapper();
final List<Trip> trips = mapper.readValue(jsonObject.getJSONArray("trips").toString(), new TypeReference<List<Trip>>() {
});
Log.i("","testVehicles maybeFetchData 12");
RealmResults<UserVehicle> completed = realm.where(UserVehicle.class).equalTo("id", userVehicleID).findAllAsync();
UserVehicle userVehicle = null;
if(completed.size() > 0){
userVehicle = completed.get(0);
}
if(userVehicle != null) {
Log.i("", "testVehicles maybeFetchData 13");
userVehicle.getTrips().clear();
Log.i("", "testVehicles maybeFetchData 14");
userVehicle.getTrips().addAll(trips);
Log.i("", "testVehicles maybeFetchData 15");
realm.copyToRealmOrUpdate(userVehicle);
Log.i("", "testVehicles maybeFetchData 16");
}else{
Log.i("", "testVehicles maybeFetchData 16 NULLLLLLLL");
}
} catch (Exception e) {
Log.i("", "fetchTripsSinceWeeksInPast fetchVehicleTrips2 error" + e.getMessage());
Utils.appendLog("ERROR fetchVehicleTrips is:" + e.getMessage(), true);
}
}
}, new Realm.Transaction.Callback() {
@Override
public void onSuccess() {
Log.i("","testVehicles maybeFetchData 17");
setPager();
Log.i("","testVehicles maybeFetchData 18");
}
@Override
public void onError(Exception e) {
Log.i("","testVehicles maybeFetchData 18 ERROR:" + e.getMessage());
}
});
}
}
});
答案 0 :(得分:3)
问题是您在异步事务中使用异步查询 - 根本不需要。
当调用realm.executeTransaction(Realm.Transaction, Realm.Transaction.Callback)
时,事务中的代码块将在一个没有looper且不需要looper的工作线程中运行。
但对于异步查询,您需要一个looper来确保查询结果可以在Android上传回。
因此,要解决您的问题,只需使用同步查询,只需让它在事务的工作线程中运行即可。为:
RealmResults<UserVehicle> completed = realm.where(UserVehicle.class).equalTo("id", userVehicleID).findAll();