Where should I write setRetryPolicy() method call when using Volley for Android development

纵然是瞬间 提交于 2019-12-11 03:59:00

问题


It might be a simple question but I tested it in actual code and unable to judge the correct behaviour of setRetryPolicy() function of Volley. Anyone please tell me the correct position of this statement to be written. Should I write this method call in onErrorResponse() function or before entering the request into the queue?

Here is my code for bitmap image. I want 3 retries of 20 seconds after request timeout. Please suggest me the correct place for retry policy to be written and have I set the retry policy correct according to my need?

ImageRequest ir = new ImageRequest(url, new Response.Listener<Bitmap>() {

            @Override
            public void onResponse(Bitmap response) {
                      iv.setImageBitmap(response);

            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                ir.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            }
        });

mRequestQueue.add(ir);

回答1:


Add the retry policy once you have declared and initialized the Request object. It's okay to add the policy anywhere before adding your request to the Volley queue.

ImageRequest  ir = new ImageRequest(url, new Response.Listener() {

        @Override
        public void onResponse(Bitmap response) {
            iv.setImageBitmap(response);
        }
    }, 0, 0, null, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //Handle errors related to Volley such as networking issues, etc
        }
});

ir.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(ir);

Another note: The onErrorResponse() callback function is used to handle errors generated from Volley. At this point, your request is already dispatched and got some networking error. Otherwise, your code would not reach this callback function. So, it's pointless to add the retry policy inside this function.



来源:https://stackoverflow.com/questions/23487556/where-should-i-write-setretrypolicy-method-call-when-using-volley-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!