Issue
I can get rowId value using an ASynctask in onPostExecute method ,I am trying to send the value back to the activity so it can be stored and used later so how to do that.
Activity :
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);
}
Repository :
public MutableLiveData<Long> insert(Note note) {
final MutableLiveData<Long> cbtId = new MutableLiveData<>();
new InsertNoteAsyncTask(noteDao, cbtId).execute(note);
return cbtId;
Async :
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 is being capture correctly in the log.d but its not sending back to the activity. I think it may be something to do with the constructor in the Async task.
Solution
Modify your insert method
public MutableLiveData<Long> insert(Note note) {
final MutableLiveData<Long> id = new MutableLiveData<>();
new InsertNoteAsyncTask(noteDao, id).execute(note);
return id;
}
Modify InsertNoteAsyncTask
construct and receive the id
. Now modify the onPostExecute method and set the id
value
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);
}
}
Now in ViewModel return the MutableLiveData and observe it in Activity. for eg:
public LiveData<Long> insertNote(Note note) {
return noteRepository.insert(note);
}
Now in Activity
, you can observe the change in the LiveData
:
viewModel.insertNote(Note).observe(this,
new Observer<Long>() {
@Override
public void onChanged(Long id) {
// do whatever you want with the id
}
});
Answered By - Deˣ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.