1

I am using Volley cache on my recycler view data. It works fine in online. When i switch to offline it displays all the data correctly but whenever i Switch back from offline to online, It creates duplicate copies on first launch while disappears on restarting the app.

Here is Main Activity code :

     private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2);

    //Displaying Progressbar
    progressBar.setVisibility(View.VISIBLE);
    setProgressBarIndeterminateVisibility(true);

    Intent intent = getIntent();
    String gradevalue = intent.getExtras().getString("gradename");

            //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.CATEGORY_URL + String.valueOf(requestCount) + Config.CATEGORY_URL2+ gradevalue ,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for (int i = 0; i < response.length(); i++) {
                        //Creating the superhero object
                        Categories gradee = new Categories();
                        JSONObject json = null;
                        try {
                            //Getting json
                            json = response.getJSONObject(i);

                            //Adding data to the superhero object
                            gradee.setImageUrl(json.getString(Config.TAG_C_IMAGE_URL));
                            gradee.setName(json.getString(Config.TAG_C_NAME));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        
                        listCategories.add(gradee);
                    }

                    //Notifying the adapter that data has been added or changed
                    adapter.notifyDataSetChanged();
                    progressBar.setVisibility(View.GONE);

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);

                }
            }) {
        @Override
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
            try {
                Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
                if (cacheEntry == null) {
                    cacheEntry = new Cache.Entry();
                }
                final long cacheHitButRefreshed = 3 * 60 * 1000; 
                final long cacheExpired = 24 * 60 * 60 * 1000; 
                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 JSONArray(jsonString), cacheEntry);
            } catch (UnsupportedEncodingException | JSONException e) {
                return Response.error(new ParseError(e));
            }
        }

        @Override
        protected void deliverResponse(JSONArray response) {
            super.deliverResponse(response);
        }

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

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

    return jsonArrayRequest;
} 
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    
    requestCount++;
} private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}


@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView1)) {
        //Calling the method getdata again
        getData();
    }
}

When Switched from Offline to Online, It gives duplicate views which disappers on restart, Heres the screenshot

: Image

If anyone can look up into code and figure out the problem, I am sure it is a minor problem. Let me know the possible ways to fix this up. Thanks.

Dhruvbhati
  • 307
  • 1
  • 13

1 Answers1

1

Not able to comment. You can put the JSON reponse into a list and clear it each time you're offline. Or put the response into a LinkedHashSet, clear the list and then populate that list with the set.

    listCategories.add(gradee));
    LinkedHashSet<Categories> set = new LinkedHashSet<>(listCategories);
                    listCategories.clear();
                    listCategories.addAll(new ArrayList<>(set));

This should remove the duplicates.

Lyra
  • 61
  • 1
  • 11