help me please how correctly i should get ontextch...
# android
a
help me please how correctly i should get ontextchanged text to viewmodel to insert to Room DB? by not destroying MVVM architecture
w
We use this way: In the `Fragment`:
Copy code
input.addTextChangedListener(object : TextWatcherAdapter() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                viewModel.onInputUpdated(s?.toString() ?: "")
            }
        })
And in the `viewModel`:
Copy code
fun onInputUpdated(text: String) {
        //Do stuff
    }
We usually also make the
object : TextWatcherAdapter
into a
val
in the
Fragment
to remove the text listener when it is destroyed.
a
thx
one more question i am getting data in init viewmodel from db and setting it to mediatorlivedata how can i put mediatorlivedata values to edittext binded mutableLivedata
w
Well, we usually don’t use the
init
method, we have our own
start
method, so we can “control” when to start, etc. Then it is straightforward, in the
Fragment
we listen for the live data, and after
start
, it will
post
the data and as the
Fragment
is listening, it will update the views.
a
in my project i am getting task key by safearg to fragment then in init block of viewmodel making this task.addSource(database.getTaskContentById(taskKey), changedEtText::setValue)
changedEdText is mutablelivedata<String>
a
If you want to get and set value to/from edit text to live data you need two-way databinding
One databinding is gonna only set values to your edit text . But judging by the fact you want to use edit text and not text view you probably want to collect user's input too otherwise one way databinding is sufficient