当前位置: 首页 > 知识库问答 >
问题:

刷新面板永远重新加载,如果一个城市没有被搜索

蓬弘
2023-03-14

我在天气应用程序上设置了一个滑动刷新面板,以便在向下滑动刷新按钮时更新从 API 收到的天气数据。当搜索城市时,此功能运行良好,但现在的问题是,如果我在向下滑动刷新面板之前尚未搜索任何城市,它将永远重新加载,直到我退出阻碍应用程序进程的应用程序,并且我的应用程序设计为在用户再次搜索城市之前不保存以前的天气数据。

我想要么在搜索城市之前完全停止刷新面板重新加载,要么只是限制在搜索城市之前重新加载所需的时间。请问我该怎么做?我已经检查了这个网站是否有类似的问题/答案,但没有发现任何有助于/与我想要实现的目标相关的问题/答案。

以下是当前的刷新面板编程设置:

realSwipe.setOnRefreshListener(() -> {
                // perform the delay action
                new Handler().postDelayed(() -> {
                    // this code is for stop refreshing icon, After 1000 ms automatically refresh icon will stop
                    realSwipe.setRefreshing(false);
                }, 1000);
            });

以下是我的代码片段(以防需要):

public class FirstFragment extends Fragment {

    private WeatherDataViewModel viewModel;

    public FirstFragment() {
    // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_first, container, false);
        // For displaying weather data
        final TextView current_temp = rootView.findViewById(R.id.textView10);
        final TextView current_output = rootView.findViewById(R.id.textView11);
        final TextView rise_time = rootView.findViewById(R.id.textView25);
        final TextView set_time = rootView.findViewById(R.id.textView26);
        final TextView temp_out = rootView.findViewById(R.id.textView28);
        final TextView Press_out = rootView.findViewById(R.id.textView29);
        final TextView Humid_out = rootView.findViewById(R.id.textView30);
        final TextView Ws_out = rootView.findViewById(R.id.textView33);
        final TextView Visi_out = rootView.findViewById(R.id.textView34);
        final TextView Cloud_out = rootView.findViewById(R.id.textView35);
        final ImageView current_icon = rootView.findViewById(R.id.imageView6);
        final SwipeRefreshLayout realSwipe = rootView.findViewById(R.id.real_swipe);

        // Get our ViewModel instance
        viewModel = new ViewModelProvider(requireActivity()).get(WeatherDataViewModel.class);

        // And whenever the data changes, refresh the UI
        viewModel.getWeatherDataLiveData().observe(getViewLifecycleOwner(), data -> {

            realSwipe.setOnRefreshListener(() -> {
                // perform the delay action
                new Handler().postDelayed(() -> {
                    // this code is for stop refreshing icon, After 1000 ms automatically refresh icon will stop
                    realSwipe.setRefreshing(false);
                }, 1000);
            });

            int drawableResource = -1; // here define default icon for example R.drawable.default_weather_icon

            int soundResource = -1; // Default sound is nothing

            if (data != null) {
                current_temp.setVisibility(View.VISIBLE);
                current_temp.setText(data.getMain().getTemp() + " ℃"); // for that you can use strings resource and templates more in https://developer.android.com/guide/topics/resources/string-resource.html#formatting-strings
                current_output.setVisibility(View.VISIBLE);
                current_output.setText(data.getWeather().get(0).getDescription());
                rise_time.setVisibility(View.VISIBLE);
                rise_time.setText(data.getSys().getSunrise() + " ");
                set_time.setVisibility(View.VISIBLE);
                set_time.setText(data.getSys().getSunset() + " ");
                temp_out.setVisibility(View.VISIBLE);
                temp_out.setText(data.getMain().getTemp() + " ℃");
                Press_out.setVisibility(View.VISIBLE);
                Press_out.setText(data.getMain().getPressure() + " hpa");
                Humid_out.setVisibility(View.VISIBLE);
                Humid_out.setText(data.getMain().getHumidity() + " %");
                Ws_out.setVisibility(View.VISIBLE);
                Ws_out.setText(data.getWind().getSpeed() + " Km/h");
                Visi_out.setVisibility(View.VISIBLE);
                Visi_out.setText(data.getVisibility() + " m");
                Cloud_out.setVisibility(View.VISIBLE);
                Cloud_out.setText(data.getClouds().getAll() + " %");

                // get actual weather.

                String icon = data.getWeather().get(0).getIcon();

                switch (icon) {
                    case "01d":
                    case "01n":
                        drawableResource = R.drawable.sun;
                        soundResource = R.raw.clear_sky_sound;
                        break;

                    case "02d":
                    case "021n":
                        drawableResource = R.drawable.few_clouds;
                        soundResource = R.raw.clouds_sound;
                        break;

                    case "03d":
                    case "03n":
                        drawableResource = R.drawable.scattered_clouds;
                        soundResource = R.raw.clouds_sound;
                        break;

                    case "04d":
                    case "04n":
                        drawableResource = R.drawable.broken_clouds;
                        soundResource = R.raw.clouds_sound;
                        break;

                    case "09d":
                    case "09n":
                        drawableResource = R.drawable.shower_rain;
                        soundResource = R.raw.shower_rain_sound;
                        break;

                    case "10d":
                    case "10n":
                        drawableResource = R.drawable.small_rain;
                        soundResource = R.raw.shower_rain_sound;
                        break;

                    case "11d":
                    case "11n":
                        drawableResource = R.drawable.thunderstorm;
                        soundResource = R.raw.thunderstorm_sound;
                        break;

                    case "13d":
                    case "13n":
                        drawableResource = R.drawable.snow;
                        soundResource = R.raw.snow_sound;
                        break;

                    case "50d":
                    case "50n":
                        drawableResource = R.drawable.mist;
                        soundResource = R.raw.mist_sound;
                        break;
                }

                if (drawableResource != -1)
                    current_icon.setImageResource(drawableResource);
                    // set the first host instance for displaying the weather icons

                if (soundResource != -1 && viewModel.soundResource != soundResource) {
                    viewModel.soundResource = soundResource;
                    if (viewModel.getMediaPlayer() != null) {
                        // we set our soundplayer in retrospect to our viewmodel

                        // stop the playing
                        if (viewModel.getMediaPlayer().isPlaying()) {
                            viewModel.getMediaPlayer().stop();
                        }

                        // release mMediaPlayer resoruces
                        viewModel.getMediaPlayer().release();
                        viewModel.setMediaPlayer(null);
                    }

                    // Play the new resource
                    viewModel.prepareMediaPlayer(requireContext(), soundResource);

                }

            } else {
                Log.e("TAG", "No City found");
                current_temp.setVisibility(View.GONE);
                current_output.setVisibility(View.GONE);
                rise_time.setVisibility(View.GONE);
                set_time.setVisibility(View.GONE);
                temp_out.setVisibility(View.GONE);
                Press_out.setVisibility(View.GONE);
                Humid_out.setVisibility(View.GONE);
                Ws_out.setVisibility(View.GONE);
                Visi_out.setVisibility(View.GONE);
                Cloud_out.setVisibility(View.GONE);
                Toast.makeText(requireActivity(), "No City found", Toast.LENGTH_SHORT).show();
            }
        });

        return rootView;
    }

    public void getWeatherData(String name) {
// The ViewModel controls loading the data, so we just
// tell it what the new name is - this kicks off loading
// the data, which will automatically call through to
// our observe() call when the data load completes
        viewModel.setCityName(name);
    }
}

共有1个答案

狄信然
2023-03-14

现在的问题是,如果我在向下滑动刷新面板之前还没有搜索任何城市,它会永远重新加载

因此,每当搜索的城市为空白/空字符串时,就会出现问题。这意味着观察到的 MutuableLiveData 回调是在这种情况上触发的。

因为我参与了你的最后一个问题;加载数据时不进行空字符串检查:

private void loadData() {
    // Get the last name that was set
    String name = state.get("name");

    // Now kick off a load from the server
    ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

    Call<Example> call = apiInterface.getWeatherData(name);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(@NonNull Call<Example> call, @NonNull Response<Example> response) {
            // Save the response we've gotten
            // This will automatically update our UI
            mutableWeatherData.setValue(response.body());
        }

        @Override
        public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
            t.printStackTrace();
        }
    });
}

要解决此问题:

  • 如果城市名称为空,请提前返回
  • 在更新 UI 之前,请检查 API 改造是否没有响应。
private void loadData() {
    // Get the last name that was set
    String name = state.get("name");
    
    // Return early if the city name is empty
    if (name == null || name.isEmpty()) return;

    // Now kick off a load from the server
    ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

    Call<Example> call = apiInterface.getWeatherData(name);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(@NonNull Call<Example> call, @NonNull Response<Example> response) {
        
            // Check if there is no response from the the Retrofit before updating the UI
            if (response.body() == null) return;
        
            // Save the response we've gotten
            // This will automatically update our UI
            mutableWeatherData.setValue(response.body());
        }

        @Override
        public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
            t.printStackTrace();
        }
    });
}

正如评论和聊天中指出的那样,所需的行为不是定期更新UI,而是让用户从顶部滑动屏幕以更新UI。

要解决< code>swipeToRefresh重新加载问题,需要将< code>swipeToRefresh侦听器从< code>LiveData观察中移除:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
                         
    // Code is omitted  ....                 
                         
     realSwipe.setOnRefreshListener(() -> {
        // perform the delay action
        new Handler().postDelayed(() -> {
            // this code is for stop refreshing icon, After 1000 ms automatically refresh icon will stop
            realSwipe.setRefreshing(false);
        }, 1000);
    });

    // And whenever the data changes, refresh the UI
    viewModel.getWeatherDataLiveData().observe(getViewLifecycleOwner(), data -> {

        int drawableResource = -1; // here define default icon for example R.drawable.default_weather_icon

        int soundResource = -1; // Default sound is nothing
        
        // Rest of the code ....
 类似资料:
  • 问题内容: 这是一个非常基本的问题-但我无法通过在线搜索找到答案。 我正在使用python控制ArcGIS,并且有一个简单的python脚本,该脚本调用了一些预先编写的代码。 但是,当我对预写代码进行更改时,它似乎没有导致任何更改。我导入了此模块,并尝试刷新它,但是没有任何反应。 我什至将它调用的文件移到了另一个位置,脚本仍然可以正常工作。昨天我做的一件事是我将所有python文件都添加到sys路

  • 问题内容: 我正在尝试实现一些功能,即单击屏幕上的按钮将导致我的[QuerydataTable刷新(因为自创建dataTable以来服务器端数据源可能已更改)。 这是我所拥有的: 但是当我运行它时,它什么也没做。单击按钮时刷新dataTable的正确方法是什么?提前致谢! 问题答案: 您可以尝试以下方法:

  • 问题内容: 我正在使用Java进行项目,因此需要在单击特定按钮后重新加载整个程序。这该怎么做? 问题答案: 尝试 如果仍然无法使用,请在完成上述步骤后尝试

  • 我想在注销后刷新/重新加载页面(屏幕上的消息在5秒钟内可见)。当前代码不会刷新它,所以我仍然在标题中看到用户名,而不是像登录按钮这样的东西。 我已经检查了这篇文章,但没有什么变化。

  • 问题内容: 我有一个带有php include的Div Tag,该div用来填充该信息,我想要做的是使它每隔15秒调用一次,以便它可以在那里更新信息,而不必重新加载整个网页。我试图用JavaScript / jQuery做到这一点,但似乎无法正常工作 这是我在搜索一些内容后所拥有的,然后发生的是,它加载了Small.php,但不会每15秒刷新一次或更新信息。 请帮忙! 我应该添加所有应显示的php

  • 该组件目前已经升级为Scroll,请移步Scroll