I am fetching weather data from an API. The problem that I am facing is when I get the cityName in textView from the current locations and then I have to send that cityName to the API so I can get the temperature of that city. But I am unable to do this. Any help will be appreciated.
HomeRepositery
suspend fun getWeatherDataFromApi(cityName : String,appid : String) =
weatherServiceApi.getchWeatherData(cityName, appid)
HomeViewModel
val weatherData: MutableLiveData<Resource<WeatherDataClass>> = MutableLiveData()
init {
getWeatherDataFromRepo("" ,"appid")
}
//here we make a network response
fun getWeatherDataFromRepo(cityName: String, appId: String) = viewModelScope.launch {
weatherData.postValue(Resource.Loading())
val response = homeRepositery.getWeatherDataFromApi(cityName, appId)
weatherData.postValue(handleWeatherResponseData(response))
}
Fragment
@SuppressLint("MissingPermission")
private fun getLocation() {
val fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(requireActivity())
val locationRequest = LocationRequest().setInterval(100000).setFastestInterval(100000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
for (location in locationResult.locations) {
latTextView.text = location.latitude.toString()
lngTextView.text = location.longitude.toString()
tv_cityName.text = getCityName(location.latitude, location.longitude)
onObserveLiveData()
}
// Few more things we can do here:
// For example: Update the location of user on server
}
},
Looper.myLooper()
)
}
private fun onObserveLiveData() {
viewModel.weatherData.observe(viewLifecycleOwner, androidx.lifecycle.Observer { response ->
when (response) {
is Resource.Success -> {
response.data?.let { weatherResponse ->
tv_humidity.text = weatherResponse.main.humidity.toString()
tv_weather.text = weatherResponse.clouds.all.toString()
tv_temp.text = weatherResponse.main.temp.toString()
}
}
is Resource.Error -> {
response.message?.let {
Toast.makeText(
requireContext(),
"THeir is am error in fetching",
Toast.LENGTH_SHORT
).show()
}
}
is Resource.Loading -> {
Toast.makeText(
requireContext(),
"Is in Loading state so please wait foe while!!",
Toast.LENGTH_SHORT
).show()
}
}
})
}