[英]How can I save user input from a textbox in my ViewModel class?
I've built a Room database in my Journaling app by following tutorials.我按照教程在我的日记应用程序中构建了一个 Room 数据库。 I've used databinding to bind my ViewModel to my Fragment and XML layout files.我使用数据绑定将我的 ViewModel 绑定到我的 Fragment 和 XML 布局文件。 In my ViewModel class, I have an onSave function that calls my DAO insert function.在我的 ViewModel 类中,我有一个调用我的 DAO 插入函数的 onSave 函数。 I set the onclick listener so that my onSave function gets called in my ViewModel when the save button is pressed.我设置了 onclick 侦听器,以便在按下保存按钮时在我的 ViewModel 中调用我的 onSave 函数。
But my user input never makes it to the ViewModel so onSave just saves nothing.但是我的用户输入从来没有进入 ViewModel 所以 onSave 什么也没有保存。 Here is the code:这是代码:
class TextEditorViewModel (val persistenceService: JournalEntryPersistenceService,
application: Application): AndroidViewModel(application) {
// This is for canceling coroutines when viewModel is destroyed
private var viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private var journalEntry = MutableLiveData<JournalEntryDataClass?>()
init {
initializeJournalEntry()
}
fun onSave(entry: JournalEntryDataClass) {
uiScope.launch {
persistenceService.insert(entry)
}
}
and和
class TextEditorFragment : Fragment() {
private lateinit var binding: TextEditorFragmentBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.text_editor_fragment, container, false)
val application = requireNotNull(this.activity).application
val persistenceService = JournalEntryDatabase.getInstance(application).journalEntryPersistenceService
val viewModelFactory = TextEditorViewModelFactory(persistenceService, application)
val textEditorViewModel = ViewModelProvider(this, viewModelFactory).get(TextEditorViewModel::class.java)
binding.setLifecycleOwner(this)
binding.textEditorViewModel = textEditorViewModel
var text = binding.journalEditTextBox.text.toString()
var journalEntry = JournalEntryDataClass(text)
binding.saveButton.setOnClickListener() { textEditorViewModel.onSave(journalEntry) }
return binding.root
}
}
Now, I have become aware that my journalEditTextBox text is being assigned as the fragment is created and thus has no data.现在,我意识到我的 journalEditTextBox 文本在创建片段时被分配,因此没有数据。 So I'm essentially sending an empty string to my onSave() function.所以我本质上是向我的 onSave() 函数发送一个空字符串。 But I'm feeling totally lost as to how I can make this work.但我对如何完成这项工作感到完全迷失。
You need to create val text inside setOnClickListener.您需要在 setOnClickListener 中创建 val 文本。
binding.saveButton.setOnClickListener() {
var text = binding.journalEditTextBox.text.toString()
var journalEntry = JournalEntryDataClass(text)
textEditorViewModel.onSave(journalEntry) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.