Search code examples
androidandroid-databindingandroid-livedata

Two way databinding not working for editText and TextView


I have implemented two-way data-binding but it is not working as expected. So here is my XML snippet :

 <EditText
            android:id="@+id/name_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:layout_marginBottom="5dp"
            android:ems="10"
            android:text="@={taskViewModel.taskName}"
            android:hint="Task name"
            android:inputType="textPersonName"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/date_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:text="@={taskViewModel.taskDate}"
            android:ems="10"
            android:drawablePadding="5dp"
            android:onClick="@{() -> listener.showDatePicker()}"
            android:drawableRight="@drawable/ic_date"
            android:hint="Pick a schedule date"
            android:inputType="textPersonName"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/time_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:text="@={taskViewModel.taskTime}"
            android:drawablePadding="5dp"
            android:ems="10"
            android:onClick="@{() -> listener.showTimePicker()}"
            android:drawableRight="@drawable/ic_time"
            android:hint="Pick a schedule time"
            android:inputType="textPersonName"
            android:textStyle="bold" />

Basically I'm trying to implement two-way data binding for the above widgets.

My ViewModel:

class TaskViewModel(private val repository: TaskRepository) : ViewModel() {
    val taskName = MutableLiveData<String>()

    val taskDate = MutableLiveData<String>()

    val taskTime = MutableLiveData<String>()


    /**
     * Launching a new coroutine to insert the data in a non-blocking way
     */
    fun insertTask() = viewModelScope.launch(Dispatchers.IO) {
        val startDate = Calendar.getInstance().time
        val scheduledDate = convertStringtoCalendar(taskDate.value, taskTime.value).time
        val diffInTime = Util.calculateDateDifference(startDate , scheduledDate)
        //User selected a proper date
        if(diffInTime > 0) {
            var newTask = Task(
                taskName = taskName.value,
                insertDate = Calendar.getInstance(),
                scheduleDate = convertStringtoCalendar(taskDate.value, taskTime.value)
            )
            val insertRowId = repository.insert(newTask)
            if (insertRowId > -1) {
                statusMessage.postValue("Task Inserted Successfully $insertRowId")
                newWordMutableLiveData.postValue(newTask)
                taskName.postValue(null)
                taskDate.postValue(null)
                taskTime.postValue(null)
            } else {
                statusMessage.postValue("Error Occured")
                newWordMutableLiveData.postValue(null)
            }
            insertRowIdMutableLiveData.postValue(insertRowId)

            Log.d("InsertId", insertRowId.toString())
        }else{
            statusMessage.postValue("Scheduled time is less than current time.")
        }
    }
}

Here you can see , I am setting the MutableLiveData to null using : taskName.postValue(null) taskDate.postValue(null) taskTime.postValue(null)

The problem is, however, the mutableLiveData values is cleared but the textViews and EditTexts text in the layout is not cleared. I need to clear them. As I am setting their corresponding MutableLiveData values to null, so they are supposed to get cleared on the insertTask() method call. But that is not the case. What wrong I am doing?


Solution

  • Find out the solution:

    The most important part , add the below line to your Activity/Fragment:

    // Required to update UI with LiveData
       dataBinding.setLifecycleOwner(this);