【问题标题】:json data repeating twice in recylerview when reloading app or when opening app重新加载应用程序或打开应用程序时,json数据在recyclerview中重复两次
【发布时间】:2017-09-24 19:19:44
【问题描述】:

谁能帮助我,我无法找出代码中的问题。我只想在应用程序启动或活动重新加载时加载一次 json 响应,但每次应用程序启动时它在 recylerview 中加载 json 响应两次,并在我的情况下从服务器检索每个 json 对象的两个副本,而在 recylerview 中总共有 50 个新闻频道25 个新闻频道的

  public class General extends Fragment  
     {

        private static final String
        URL = "https://newsapi.org/v1/sources?language=en&category=general&apiKey=0e1b2f7bc6bd4e1fbe0b40bea257dc97";
        private final int android_image_urls[] = 
      {
        R.drawable.abcnews,
        R.drawable.aljazeera,
        R.drawable.associatedpress,
        R.drawable.bbcnews,
        R.drawable.cnn,
        R.drawable.googlenews,
        R.drawable.independent,
        R.drawable.metro,
        R.drawable.mirror,
        R.drawable.newsweek,
        R.drawable.newyorkmagazine,
        R.drawable.reddit,
        R.drawable.reuters,
        R.drawable.theguardianau,
        R.drawable.theguardianuk,
        R.drawable.thehindu,
        R.drawable.thehuffingtonpost,
        R.drawable.thenewyorktimes,
        R.drawable.thetelegraph,
        R.drawable.thetimesofindia,
        R.drawable.thewashingtonpost,
        R.drawable.time,
        R.drawable.usatoday
   }; 

   private RecyclerView recyclerView;
   private RecyclerView.Adapter adapter;
   private ArrayList<AndroidVersion> androidVersions;

  TextView textView;

  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.layout_general, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(),3);
    recyclerView.setLayoutManager(layoutManager);
    textView = (TextView) rootView.findViewById(R.id.empty_view);
    androidVersions = new ArrayList<>();
    loadRecyclerViewData();
    return rootView;
    }


   public void loadRecyclerViewData() {

    final ProgressDialog progressDialog = new ProgressDialog(getContext());
    progressDialog.setMessage("Loading Data....");
    progressDialog.show();


    JsonObjectRequest data = new JsonObjectRequest(Request.Method.GET, URL,null,

            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    progressDialog.dismiss();

                    try {
                        JSONObject jsonObject = new JSONObject(String.valueOf(response));

                        JSONArray array = jsonObject.getJSONArray("sources");

                        for (int i = 0; i < array.length(); i++) {
                            JSONObject o = array.getJSONObject(i);
                            AndroidVersion item = new AndroidVersion(

                                    o.getString("name"),
                                    android_image_urls[i],
                                    o.getString("category")
                            );
                            androidVersions.add(item);

                        }


                        if (androidVersions.isEmpty()) {
                            recyclerView.setVisibility(View.GONE);
                            textView.setVisibility(View.VISIBLE);
                        } else {
                            recyclerView.setVisibility(View.VISIBLE);
                            textView.setVisibility(View.GONE);
                        }

                        adapter = new DataAdapter(androidVersions, getContext());
                        recyclerView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            progressDialog.dismiss();
            Toast.makeText(getContext(),"No Internet Connection", Toast.LENGTH_SHORT).show();

        }
    })
    {
    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
        if (cacheEntry == null) {
            cacheEntry = new Cache.Entry();
        }
        final long cacheHitButRefreshed = 3 * 60*1000; // in 3 minutes cache will be hit, but also refreshed on background
        final long cacheExpired = 24 * 60 * 1000 ; //24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
        long now = System.currentTimeMillis();
        final long softExpire = now + cacheHitButRefreshed;
        final long ttl = now + cacheExpired;
        cacheEntry.data = response.data;
        cacheEntry.softTtl = softExpire;
        cacheEntry.ttl = ttl;
        String headerValue;
        headerValue = response.headers.get("Date");
        if (headerValue != null) {
            cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        headerValue = response.headers.get("Last-Modified");

        if (headerValue != null)
        {
            cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        cacheEntry.responseHeaders = response.headers;
        final String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString), cacheEntry);
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException e) {
        return Response.error(new ParseError(e));
    }
    }
        @Override
        protected void deliverResponse(JSONObject response) {
            super.deliverResponse(response);
        }

        @Override
        public void deliverError(VolleyError error) {
            super.deliverError(error);
        }

        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            return super.parseNetworkError(volleyError);
        }
};

RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(data);
}

}

【问题讨论】:

  • 在向它添加项目之前清除 ArrayList androidVersions.clear() 并且不使用 adapter.notifyDataSetChanged() 所以你可以删除它。
  • 非常感谢吉塔,它就像魅力一样。

标签: android json android-recyclerview android-volley


【解决方案1】:

您的代码是正确的,它不能显示重复数据,请尝试删除数据缓存

【讨论】:

  • rajendra 您正在写关于删除数据捕获的文章互联网连接不可用时处于离线状态,这种情况下我该怎么办?
【解决方案2】:

在你onResponse 中,你没有清理androidVersions 列表。因此,每次执行您的请求时,您都会将新项目添加到您的列表中。很可能您的请求被执行了两次(loadRecyclerViewData() 被调用了两次?)。

每次填写onResponse时尝试清理或重新创建androidVersions

【讨论】:

  • 感谢 algrid 提供的解决方案,但您能否详细解释一下您所说的内容,例如清除列表的程序,因为我是第一次做这件事
  • 请告诉我我应该如何以编程方式实现你所说的?
猜你喜欢
  • 1970-01-01
  • 2023-01-28
  • 2015-12-23
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多