基本上我试图在尝试使用它之前检查某个对象是否存在,如果没有,我会事先添加它然后尝试使用它。
如果它不存在,它会被正确添加,但之后应用程序仍然找不到它,除非我重新打开该应用程序
如果对象以
开头,那么一切都按预期工作private class ExerciseViewPageAdapter extends FragmentPagerAdapter {
Realm realm;
ExerciseViewPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
realm = Realm.getDefaultInstance();
String exercise_name = getIntent().getExtras().getString("exercise_name");
boolean found_exercise = realm.where(Exercise.class).equalTo("name", exercise_name).findAll().size() > 0;
if (!found_exercise) {
CompositeDisposable disposable = new CompositeDisposable();
ExerciseClient client = new ExerciseClient(getApplicationContext());
disposable.add(client.getExerciseByName(exercise_name)
.subscribeOn(Schedulers.io())
.subscribe(
this::getExercisesSuccess,
this::getExercisesError
)
);
}
final ArrayList<Exercise> exercise = new ArrayList<>();
exercise.add(realm.where(Exercise.class).equalTo("name", exercise_name).findFirst());
if (exercise.get(0) != null) {
switch (pos) {
//returning new fragments depending on position
}
}
//if exercise.get(0) doesn't exist at first, even tho I added it afterwards it's still null here unless I reopen the app or let it crash
finish();
realm.close();
return null;
}
private void getExercisesError(Throwable throwable) {
}
private void getExercisesSuccess(Exercise exercise) {
try (Realm r = Realm.getDefaultInstance()) {
r.executeTransaction(realm -> {
realm.insertOrUpdate(exercise);
});
}
}
@Override
public int getCount() {
return 3;
}
}
编辑:TL; DR:问题是realm.where()...
只有在重新打开应用程序后再插入对象后才会看到该对象
答案 0 :(得分:3)
你打电话给api,它会在后台运行,所以在api调用上编写的代码将会执行。因此,您的活动将自动关闭。
请求您的api成功失败验证
private void getExercisesSuccess(Exercise exercise) {
try (Realm r = Realm.getDefaultInstance()) {
r.beginTransaction();
realm.insertOrUpdate(exercise);
r.commitTransaction();
//checking records are in realm
final ArrayList<Exercise> exercise = new ArrayList<>();
exercise.add(realm.where(Exercise.class).equalTo("name", exercise_name).findFirst());
if (exercise.get(0) != null) {
switch (pos) {
//returning new fragments depending on position
}
}
//if exercise.get(0) doesn't exist at first, even tho I added it afterwards it's still null here unless I reopen the app or let it crash
finish();
realm.close();
}catch(Exception e){}
}
从getItem()
中删除以下行 final ArrayList<Exercise> exercise = new ArrayList<>();
exercise.add(realm.where(Exercise.class).equalTo("name", exercise_name).findFirst());
if (exercise.get(0) != null) {
switch (pos) {
//returning new fragments depending on position
}
}
//if exercise.get(0) doesn't exist at first, even tho I added it afterwards it's still null here unless I reopen the app or let it crash
finish();
realm.close();