Reputation: 425
I've built a Room database in my Journaling app by following tutorials. I've used databinding to bind my ViewModel to my Fragment and XML layout files. In my ViewModel class, I have an onSave function that calls my DAO insert function. I set the onclick listener so that my onSave function gets called in my ViewModel when the save button is pressed.
But my user input never makes it to the ViewModel so onSave just saves nothing. 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. So I'm essentially sending an empty string to my onSave() function. But I'm feeling totally lost as to how I can make this work.
Upvotes: 1
Views: 1540
Reputation: 867
You need to create val text inside setOnClickListener.
binding.saveButton.setOnClickListener() {
var text = binding.journalEditTextBox.text.toString()
var journalEntry = JournalEntryDataClass(text)
textEditorViewModel.onSave(journalEntry) }
Upvotes: 1