首页 > 解决方案 > 如何发送多个 api 请求并在 RecyclerView 中显示结果?

问题描述

我试图弄清楚如何从我的房间数据库中获取城市,将每个城市的 api 请求发送到 openweathermap 并在 RecyclerView 中显示结果。我正在使用改造的 for 循环中向 openweathermap 发送 api 请求,但它无法正常工作。我的数据库中有 5 个城市,我的日志中只有 3 个“完成”,而我的 RecyclerView 只显示 1 个项目。所以我必须以完全错误的方式这样做。有谁知道如何以正确的方式做到这一点?

我的片段:

public class SavedLocationsFragment extends Fragment {

    private FragmentSavedLocationsBinding binding;
    private SavedLocationsViewModel savedViewModel;
    private SavedLocationsAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_saved_locations, container, false);
        View view = binding.getRoot();

        //creating an instance of SavedLocationsViewModel and binding it
        savedViewModel = new ViewModelProvider(this).get(SavedLocationsViewModel.class);
        binding.setLifecycleOwner(this);
        binding.setViewmodel(savedViewModel);

        //RecyclerView and Adapter
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        adapter = new SavedLocationsAdapter();
        binding.recyclerView.setAdapter(adapter);

        savedViewModel.getAllCities().observe(getViewLifecycleOwner(), cities -> savedViewModel.getCitiesWithData(cities));
        savedViewModel._weatherResponse.observe(getViewLifecycleOwner(), weatherList -> {
            adapter.submitList(weatherList);
        });

        return view;
    }
}

视图模型:

public class SavedLocationsViewModel extends AndroidViewModel {
    private CityRepository repository;
    private LiveData<List<City>> allCities;
    public MutableLiveData<List<WeatherResponseCurrent>> _weatherResponse = new MutableLiveData<>();

    public SavedLocationsViewModel(@NonNull Application application) {
        super(application);
        repository = new CityRepository(application);
        allCities = repository.getAllCities();
    }

    public LiveData<List<City>> getAllCities() {
        return allCities;
    }

    public void getCitiesWithData(List<City> cities) {

        List<WeatherResponseCurrent> list = new ArrayList<>();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.openweathermap.org/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        WeatherServiceCurrent service = retrofit.create(WeatherServiceCurrent.class);

        for(int i=0; i<cities.size(); i++) {

            Call<WeatherResponseCurrent> call = service.getCurrentWeatherData(allCities.getValue().get(i).getName(), "ru", "metric", "my_api_key");
            call.enqueue(new Callback<WeatherResponseCurrent>() {
                @Override
                public void onResponse(Call<WeatherResponseCurrent> call, Response<WeatherResponseCurrent> response) {
                    if (response.code() == 200) {
                        WeatherResponseCurrent weatherResponse = response.body();
                        assert weatherResponse != null;
                        list.add(weatherResponse);
                        _weatherResponse.postValue(list);
                        Log.d("SavedLocationsViewModel", "Done!!!");
                    }
                }

                @Override
                public void onFailure(Call<WeatherResponseCurrent> call, Throwable t) {
                    Log.d("SavedLocationsViewModel", t.getMessage());
                }
            });
        }

    }

}

标签: androidnetworkingandroid-recyclerviewretrofit2

解决方案


推荐阅读