Когда я нажимаю кнопку «Получить погоду» , я хочу, чтобы TextView немедленно отображал полученные данные о погоде, но в настоящее время он остается пустым, пока я не поверну экран или не изменю конфигурацию.
Настройка кода:
WeatherFragment.java:
В этом фрагменте я инициализирую WeatherViewModel и наблюдаю за getWeatherData() в onViewCreated.
При нажатии кнопки я вызываю WeatherViewModel.fetchWeatherData(city) для получения данных на основе пользовательского ввода.
/>
Код: Выделить всё
public class WeatherFragment extends Fragment {
private WeatherViewModel weatherViewModel;
private FragmentWeatherBinding binding;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentWeatherBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
weatherViewModel = new ViewModelProvider(this).get(WeatherViewModel.class);
binding.buttonFetchWeather.setOnClickListener(v -> {
String city = binding.editTextCity.getText().toString().trim();
if (!city.isEmpty()) {
weatherViewModel.fetchWeatherData(city); // Retrieve weather data for the city
} else {
binding.textViewWeather.setText("Please enter a city name.");
}
});
weatherViewModel.getWeatherData().observe(getViewLifecycleOwner(), weatherData -> {
if (weatherData != null) {
binding.textViewWeather.setText(weatherData);
}
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null; // Avoid memory leaks
}
}
В Weatherwiewmodel я вызываю Fetchweatherdata (город), чтобы запустить вызов API и установить результат в MutableLivedata.
Код: Выделить всё
package com.example.weather;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class WeatherViewModel extends ViewModel {
private final WeatherRepository repository;
private MutableLiveData weatherResult = new MutableLiveData();
public WeatherViewModel() {
repository = new WeatherRepository();
}
public void fetchWeatherData(String city) {
weatherResult = repository.getWeather(city);
}
public LiveData getWeather() {
return weatherResult;
}
}
Переместил наблюдатель для getWeatherData() в onCreateView, но поведение такое же.Вопрос:
Почему LiveData запускает обновление только после изменения конфигурации и как я могу быть уверен, что TextView обновляется сразу же, когда я нажимаю кнопку? Связана ли проблема с асинхронным поведением fetchWeatherData(city), и если да, то как заставить ее запускать немедленное обновление?
Будем очень благодарны за любую помощь или информацию! Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/791 ... uration-ch
Мобильная версия