【发布时间】:2018-06-16 05:43:32
【问题描述】:
活动接收意图
class AddNoteActivity : AppCompatActivity() {
private lateinit var addViewModel: NoteViewModel
private lateinit var titleEditText: TextInputEditText
private lateinit var contentEditText: TextInputEditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_note_activty)
setSupportActionBar(toolbar)
addViewModel = ViewModelProviders.of(this).get(NoteViewModel::class.java)
titleEditText = findViewById(R.id.itemTitle)
contentEditText = findViewById(R.id.itemNote)
val extra = intent.extras
if (extra != null) {
val uuid = extra.getLong("UUID")
val note: Notes? = addViewModel.getNote(uuid)
titleEditText.setText(note!!.title)
contentEditText.setText(note.note)
}
}
}
NoteViewModel 类
class NoteViewModel(application: Application) : AndroidViewModel(application) {
companion object {
private var note: Notes = Notes(0, "", "test title", "test ontent")
}
fun getNote(uuid: Long?): Notes {
val job = async(CommonPool) {
getNoteAsyncTask(notesDatabase).execute(uuid)
}
runBlocking { job.await() }
return note
}
class getNoteAsyncTask(database: NotesDatabase) : AsyncTask<Long, Unit, Unit>() {
private val db: NotesDatabase = database
override fun doInBackground(vararg params: Long?) {
note = db.notesDataDao().getNote(params[0])
}
}
}
如果我通过一个意图从数据库中获取一个带有 uuid 的 Note 对象,并在 titleEditText 和 contentEditText 中设置接收到的数据,那么 Note 中的数据集来自我们单击 RecyclerView 中的 Note 项时调用的先前意图。第一次点击Note项时,我得到了我设置的“测试标题”和“测试内容”的默认值。
上述是大多数时候的行为。有时,titleEditText 和 contentEditText 中的数据集是正确的 Note 对象。
谁能告诉我我做错了什么?如何纠正我的应用行为?
【问题讨论】:
-
您能否在您的 dao 类中发布您的 getNote() 方法。
-
@rafa @Query("SELECT * from notes where uuid LIKE :noteId") fun getNote(noteId: Long?) : Notes
标签: android kotlin android-room kotlinx.coroutines