Menu
Who Do Is
  • Home
  • What
  • How
  • Is
  • Can
  • Are
  • Does
  • Do
  • Why
  • Who
  • Where
  • Which
  • Which
  • Should
  • Will
  • When
  • What’s
  • Did
Who Do Is

[ANSWERED] Android Volley Cache Creates Duplicates

Posted on November 14, 2022

Solution 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.

Problem :

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

READ  [ANSWERED] react native - expo-payments-stripe doesn't work on real android device
Powered by Inline Related Posts

: 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.

Comments

Comment posted by Dhruvbhati

please help guys

Comment posted by Dhruvbhati

please assist me guys

Comment posted by Dhruvbhati

i Dont understand where to implement it in my code?

Comment posted by Lyra

Made little modification to my answer. You can add it where you populate the list: below listCategories.add(gradee)

Comment posted by james04

Switch to retrofit 🙂

Comment posted by Dhruvbhati

Hey, I was wondering which method calls when there is no cache data to display, i want to display a toast there. Could you please help?

Comment posted by Lyra

I don’t understand your question. Can you rephrase it?

Recent Posts

  • How can I play with my cat without toys?
  • What is a bag pipe band called?
  • Are Honda Civics actually fast?
  • Are Yankee candles toxic?
  • How do I pair my Michael Kors smartwatch with my Android?

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuántas
  • ¿Cuánto
  • ¿Que
  • ¿Quién
  • 90” and 108” so you may have to round up to the nearest size.
  • and delete any Spotify folders from it. Once this is done
  • Android
  • Are
  • At
  • Bei
  • blink
  • C'est
  • Can
  • carbs
  • Comment
  • Did
  • Do
  • Does
  • During
  • For
  • Has
  • How
  • In
  • Is
  • Ist
  • Kann
  • Können
  • nouveau
  • On
  • or 108 inches.2020-08-03
  • Où
  • owning
  • Pourquoi
  • Puis-je
  • Quand
  • Quante
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • spiritual
  • tap the downward-facing arrow on the top left. A downward-facing arrow will appear underneath each song in the album; they'll turn green as the download completes.2020-07-28
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welcher
  • Welches
  • Welke
  • Wer
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Whose
  • Why
  • Wie
  • Will
  • Wo
  • Woher
  • you will receive two curtains each with the same measurements of width 66"" (168cm) x drop 54""(137cm).
  • you'll see a green downward-facing arrow next to each song.2021-02-26
©2023 Who Do Is | Powered by SuperbThemes & WordPress