【问题标题】:Refresh JSON Data (OnCreate, OnCreateView, OnResume) and Cache刷新 JSON 数据(OnCreate、OnCreateView、OnResume)和缓存
【发布时间】:2022-01-19 17:07:37
【问题描述】:

Android 工作室,我正在使用以下内容从服务器上的 json 文件中解析 videoid。

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_radio, container, false);
YTApiResult = view.findViewById(R.id.APIResult);

String url = "https://myserver.com/example.json";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray jsonArray = response.getJSONArray("items");

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.optJSONObject(i);
                        JSONObject jsonArray1 = jsonObject.getJSONObject("id");
                        String videoid = jsonArray1.optString("videoId");
                        initYouTubePlayerView(videoid);
                        YTApiResult.setText("STATUS: " + videoid);
                        livevideoid=videoid;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO: Handle error
            }
        });

MySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);

这一切似乎都正常工作。在应用启动时,从我服务器的 json 文件中正确提取了 videoid。

我似乎遇到的问题是 json 文件中的 videoid 仅在安装应用程序时更新一次。如果我更新服务器上 json 文件中的 videoid,然后打开应用程序(在初始安装后),它不会更新 videoid。

如果我随后卸载并重新安装应用程序,它会更新 - 但不是在每次启动应用程序时。

我以为因为它在 OnCreate 中,所以它会在每次打开片段页面时从 url 自动更新 json videoid,但似乎没有。

我还尝试在 onResume 中使用所有以前的代码,我知道每次都会使用 log.d 调用它,但如果不卸载/重新安装应用程序,它仍然不会更新。我假设我缺少某种代码来刷新数据,但我对此很陌生。

public void onResume(){
        super.onResume();
        Log.d("testTag", "OnResume started");

所以,我的问题是:如何在每次打开应用程序或片段时更新 videoid?

【问题讨论】:

    标签: java android json


    【解决方案1】:

    onCreate 在生命周期中调用一次。如果您想在屏幕处于焦点时更新或刷新数据,您可以尝试使用 onStart 方法。每次屏幕处于焦点时都会调用 onstart 和 onresume。

    【讨论】:

      【解决方案2】:

      好的,所以问题不在于 onCreate、onCreateView 或 onResume。问题是我的服务器正在缓存 json 文件,所以当我在服务器上更新 json 文件时,应用程序仍在拉取旧的缓存文件。

      我的解决方案是实施

      String url = "https://myserver.com/example.json?_cache_buster=" + new Date().getTime();
      

      添加日期/时间参数以强制其不缓存。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-27
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多