我在 Loopers 和 Realm 上遇到了麻烦。
我在 onCreate() 中有一个Activity
实例化它Presenter
,然后调用它的一个公共方法initFirstLaunch()
:
RealmChangeListener<CourseDetailed> listener = new RealmChangeListener<CourseDetailed>() {
@Override
public void onChange(CourseDetailed element) {
Log.i("renaud", "courseDetailed.addChangeListener onChange");
computeTableOfContent(element);
Log.i("renaud", "1");
playerViewContract.initWithCourseDetails(element);
Log.i("renaud", "2");
}
};
public void initFirstLaunch() {
courseDetailed = realm.where(CourseDetailed.class).contains("_id", courseId).findFirst();
if (courseDetailed == null) {
courseDetailed = realm.createObject(CourseDetailed.class, courseId);
}
courseDetailed.addChangeListener(listener);
Api.getInstance().backend.getCourse(courseId).enqueue(new CustomRetrofitCallBack<CourseDetailed>(playerViewContract) {
@Override
public void onResponseReceived(final CourseDetailed response) {
Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response);
}
});
}
});
}
请注意,这playerViewContract
是我在这种情况下的活动。
我的问题是onChange()
有时会调用它,当它调用时它会阻塞我的 UI 线程(并最终引发 a OutOfMemoryError
)。我的猜测是我不在一个弯针线程中,但是当我Looper.prepare()
在任何地方打电话时它崩溃说我已经在一个。
发生了什么 ?
谢谢
编辑:添加 initWithCourseDetailed 代码
@Override
public void initWithCourseDetails(final CourseDetailed detailed) {
Log.i("renaud", "initWithCourseDetails");
mDrawer.post(new Runnable() {
@Override
public void run() {
String title = detailed.getName();
String subtitle = detailed.getCompany().getName();
if (detailed.getThumbnail() != null) {
String picUrl = AppConstants.SERVER_URL + "/api/" + detailed.getThumbnail();
final LinearLayout l = (LinearLayout) mNavigationView.findViewById(R.id.layout);
Picasso.with(ModulePlayerActivity.this)
.load(picUrl)
.config(Bitmap.Config.RGB_565)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
l.setBackground(new BitmapDrawable(getResources(), bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
TextView nameTv = (TextView) mNavigationView.findViewById(R.id.drawer_header_name);
nameTv.setText(title);
TextView jobTv = (TextView) mNavigationView.findViewById(R.id.drawer_header_job);
jobTv.setText(subtitle);
supportInvalidateOptionsMenu();
}
});
}
编辑:更正
Api.getInstance().backend.getCourse(courseId).enqueue(new CustomRetrofitCallBack<CourseDetailed>(playerViewContract) {
@Override
public void onResponseReceived(final CourseDetailed response) {
//TEST
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response);
}
});
} finally {
if (realm != null) {
realm.close();
}
realm = null;
}
}
});