我有一个从SQlite数据库返回的主键。我需要将其从存储库类传递给活动。但是我不知道如何。有关上下文和逻辑,请参见下面的代码。
主要活动:
private void insertWorkingNoReturn() {
String automaticThoughtString = automaticThoughtET.getText().toString().trim();
Note note = new Note(userId, therapistId, automaticThoughtString, 0, "", "", postedWorkout);
try {
viewModel.insert(note).observe(NoteActivity.this, new androidx.lifecycle.Observer<Resource<Integer>>() {
@Override
public void onChanged(Resource<Integer> integerResource) {
try {
if (integerResource != null) {
switch (integerResource.status) {
case SUCCESS: {
Log.e(TAG, "onChanged: save note: success...");
Log.d(TAG, "insert: +" + integerResource.message);
Log.d(TAG, "AutomaticThought" + sqCbtId);
break;
}
case ERROR: {
Log.e(TAG, "onChanged: save note: error...");
Log.d(TAG, "insert: +" + integerResource.message);
break;
}
case LOADING: {
Log.e(TAG, "onChanged: save note: loading...");
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "insert: +" + e.getMessage());
}
}
存储库:
public Flowable<Resource<Integer>> insert(final Note note) throws Exception {
checkTitle(note);
return noteDao.insert(note)
.delaySubscription(timeDelay, timeUnit)
.map(new Function<Long, Integer>() {
@Override
public Integer apply(Long aLong) throws Exception {
long l = aLong;
return (int) l;
}
})
.onErrorReturn(new Function<Throwable, Integer>() {
@Override
public Integer apply(Throwable throwable) throws Exception {
return -1;
}
})
.map(new Function<Integer, Resource<Integer>>() {
@Override
public Resource<Integer> apply(Integer integer) throws Exception {
if (integer > 0) {
return Resource.success(integer, INSERT_SUCCESS);
}
return Resource.error(null, INSERT_FAILURE);
}
})
.subscribeOn(Schedulers.io())
.toFlowable();
因此,主活动中的Method进行插入,该插入仅将方法调用传递给viewmodel。视图模型将其传递到存储库,并且清单中的方法会激活到执行插入操作的NoteDAO类。然后,主键作为long返回,并转换为Repository类中的int。但是我不知道如何在主类中访问该变量。