Java Android MVVM-如何将存储库中的变量发送回活动?

时间:2019-07-12 17:36:35

标签: android mvvm android-asynctask

我可以使用 onPostExecute方法中的ASynctask获得 rowId值,我正尝试将该值发送回活动,以便以后可以存储和使用,如何为此。

活动:

Note note = new Note(userId, therapistId, automaticThoughtString,  distortions, challengeThoughtString, alternativeThoughtString, postedWorkout);
             noteViewModel.insert(note).observe(WorkoutAutomaticThoughtActivity.this, new Observer<Long>() {
                @Override
                public void onChanged(Long cbtId) {

                    sqCbtId = cbtId;
                    Log.d(TAG, "AutomaticThought" + sqCbtId);
                }
            });

Viewmodel:

 public LiveData<Long> insert (Note note) {
    return repository.insert(note);  
} 

存储库:

    public MutableLiveData<Long> insert(Note note) {
    final MutableLiveData<Long> cbtId = new MutableLiveData<>();
    new InsertNoteAsyncTask(noteDao, cbtId).execute(note);
    return cbtId; 

异步:

 public InsertNoteAsyncTask(NoteDao noteDao, MutableLiveData<Long> cbtId) {
    this.noteDao = noteDao;
}

@Override
protected Void doInBackground(Note... notes) {
    sqCbtId = noteDao.insert(notes[0]);
    return null;
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    getCbtId(sqCbtId);
    Log.d(TAG, "onPostExecuteAsync: " + sqCbtId);
}

public void getCbtId(long cbtId) {
    sqCbtId = cbtId;
}

CbtId已在log.d中正确捕获,但没有发送回活动。我认为这可能与Async任务中的构造函数有关。

1 个答案:

答案 0 :(得分:0)

修改您的插入方法

public MutableLiveData<Long> insert(Note note) {
 final MutableLiveData<Long> id = new MutableLiveData<>();
 new InsertNoteAsyncTask(noteDao, id).execute(note); 
 return id;
}

修改InsertNoteAsyncTask的构造并接收id。现在,修改onPostExecute方法并设置id

   class InsertNoteAsyncTask extends AsyncTask<Note, Void, Long> {
    private NoteDao noteDao;
    private MutableLiveData<Long> id;
     public InsertNoteAsyncTask(NoteDao noteDao, MutableLiveData<Long> id) {
        this.noteDao = noteDao;
        this.id = id;
     }

     @Override
     protected Long doInBackground(Note... notes) {
        long sqCbtId = noteDao.insert(notes[0]);
        return sqCbId;
     }

     @Override
     protected void onPostExecute(Long sqCbtId) {
        super.onPostExecute(result);
        id.setValue(sqCbtId); 
        Log.d(TAG, "onPostExecuteAsync: " + sqCbtId);
     }
    }

现在,在ViewModel中返回MutableLiveData并在Activity中进行观察。例如:

public LiveData<Long> insertNote(Note note) {
  return noteRepository.insert(note);
}

现在在Activity中,您可以观察到LiveData中的变化:

viewModel.insertNote(Note).observe(this,
        new Observer<Long>() {
          @Override
          public void onChanged(Long id) {
            // do whatever you want with the id
          }
        });