1

I'm creating the app uses API and I have function inside the ViewModel which needs name of the city to fetch data from web. But it does not work. I have already worked with two way data binding in Java Android, but in Kotlin case something is wrong. In the CityViewModel I have an ObservableField which is binded with an Edit Text. This is place for name of city, then after button click is launching val currentWeatherByCity, but in logs is response error from API. If I set just string to the currentWeatherByCity as for example "London" API works, but if I want to use ObservableField app crashes.

CityViewModel:

class CityViewModel(
private val weatherRepository: WeatherRepository
): ViewModel() {

val city = ObservableField<String>()
private val metric: String = "metric"


val currentWeatherByCity by lazyDeferred {
    weatherRepository.getCurrentWeatherByCity(city.get().toString(), metric)
}

}

CityActivity:

 private fun bindUI() = launch(Dispatchers.Main) {
    val cityWeather = cityViewModel.currentWeatherByCity.await()
    cityWeather.observe(this@CityActivity, Observer {
        if (it == null) return@Observer


    })

ActivityCity xml:

<EditText android:layout_width="match_parent"
                  android:layout_height="50dp"
                  app:layout_constraintTop_toTopOf="parent"
                  android:gravity="center"
                  android:foregroundGravity="center_vertical"
                  android:textColor="@android:color/white"
                  android:textSize="20sp"
                  android:text="@={cityViewModel.city}"
                  android:hint="London/London,uk"
                  android:id="@+id/city_edit_text"
                  android:layout_marginEnd="50dp"
                  app:layout_constraintEnd_toStartOf="@+id/search_city_button"
                  android:inputType="text"
                  android:autofillHints="username"/>

I also checked the ObservableField in logs and city is null. If I set the String inside ObservableField then is right and API fetches data.

beginner992
  • 659
  • 1
  • 9
  • 28

0 Answers0