重新加载应用程序或打开应用程序时,json数据在recylerview中重复两次

时间:2017-09-24 19:19:45

标签: android json android-recyclerview android-volley

任何人都可以帮助我,我无法弄清楚代码中的问题。我只想在应用程序启动或活动重新加载时加载一次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);
}

}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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