0

I want to create one base class for volley library and want to access the response and Error on the Activity where i called the volley request.because of this my code will optimize.

asiya
  • 280
  • 1
  • 5
  • 16
  • IMO, pls read the following links http://stackoverflow.com/questions/33535435/how-to-create-a-proper-volley-listener-for-cross-class-volley-method-calling/33535554#33535554 and http://stackoverflow.com/questions/31602042/android-java-how-to-delay-return-in-a-method – BNK Nov 25 '15 at 12:58
  • https://stackoverflow.com/a/44470827/3395198 – IntelliJ Amiya Jun 10 '17 at 07:42

2 Answers2

0

Personally am using following classes for handling volley.you can revert it as per the requirement.

Volley Request Queue Helper :

public class VolleyHelper {

    private static final String TAG = VolleyHelper.class
            .getSimpleName();

    private RequestQueue mRequestQueue;
    private static VolleyHelper mInstance;

    public VolleyHelper (Context context) {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }
    }

    public static synchronized VolleyHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleyHelper(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Ideally you should have one centralized place for your Queue, and the best place to initialize queue is in your Application class. Above snippet interpret how this can be done

Volley Error Helper

public class VolleyErrorHelper {
    /**
     * Returns appropriate message which is to be displayed to the user
     * against the specified error object.
     *
     * @param error
     * @param context
     * @return
     */
    public static String getMessage(Object error, Context context) {
        if (error instanceof TimeoutError) {
            return context.getResources().getString(R.string.generic_server_down);
        } else if (isServerProblem(error)) {
            return handleServerError(error, context);
        } else if (isNetworkProblem(error)) {
            return context.getResources().getString(R.string.no_internet);
        }
        return context.getResources().getString(R.string.generic_error);
    }

    /**
     * Determines whether the error is related to network
     *
     * @param error
     * @return
     */
    private static boolean isNetworkProblem(Object error) {
        return (error instanceof NetworkError) || (error instanceof NoConnectionError);
    }

    /**
     * Determines whether the error is related to server
     *
     * @param error
     * @return
     */
    private static boolean isServerProblem(Object error) {
        return (error instanceof ServerError) || (error instanceof AuthFailureError);
    }

    /**
     * Handles the server error, tries to determine whether to show a stock message or to
     * show a message retrieved from the server.
     *
     * @param err
     * @param context
     * @return
     */
    private static String handleServerError(Object err, Context context) {
        VolleyError error = (VolleyError) err;

        NetworkResponse response = error.networkResponse;

        if (response != null) {
            switch (response.statusCode) {
                case 409:
                    return context.getResources().getString(R.string.user_exists);
                case 404:
                    break;
                case 422:
                    break;
                case 401:
                    try {
                        // server might return error like this { "error": "Some error occured" }
                        // Use "Gson" to parse the result
                        HashMap<String, String> result = new Gson().fromJson(new String(response.data),
                                new TypeToken<Map<String, String>>() {
                                }.getType());

                        if (result != null && result.containsKey("error")) {
                            return result.get("error");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // invalid request
                    return error.getMessage() != null ? error.getMessage() : context.getResources().getString(R.string.generic_error);

                default:
                    return context.getResources().getString(R.string.generic_server_down);
            }
        }
        return context.getResources().getString(R.string.generic_error);
    }
}

Volley Response Helper

public class VolleyResponseHelper {
    /**
     * Returns appropriate message which is to be displayed to the user
     * against the specified response .
     *
     * @param code
     * @param context
     * @return
     */
     /* 0 - Request from registration */
    /* 1 - Request from login */
    /* 2 - Request from New post */
    public static String getMessage(String code, int from, Context context) {
        int mCode = Integer.parseInt(code);
        String message = null;
        switch (mCode) {
            case 409:
                if (from == 1 || from == 0) {
                    message = context.getResources().getString(R.string.user_exists);
                }
                return message;
            case 200:
                if (from == 1 || from == 0) {
                    message = context.getResources().getString(R.string.success);
                } else if (from == 2) {
                    message = context.getResources().getString(R.string.np_done);
                }
                return message;
            case 401:
                if (from == 1) {
                    message = context.getResources().getString(R.string.user_not_exists);
                }
                return message;

            default:
                return context.getResources().getString(R.string.generic_error);
        }

    }


}

Inside volley onErrorResponse

           @Override
            public void onErrorResponse(VolleyError error) {
                String errorString = VolleyErrorHelper.getMessage(error, context);
                if (errorString != null) {
                   showAlert(errorString);
                }
            }

For more clear about usage i have posted my code revert it like your requirement

 private void getDetails(Map<String, String> params) {
        SalonJsonObjReq arrayReq = new SalonJsonObjReq(Request.Method.POST, Constants.SALON_DETAILS, new JSONObject(params), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                populate(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                hideProgressDialog();
                String errorString = VolleyErrorHelper.getMessage(error, DetailsScreen.this);
                if (errorString != null) {
                    Util.showAlert(DetailsScreen.this, getResources().getString(R.string.error), errorString);
                }
            }
        }, null);
        showProgressDialog(getResources().getString(R.string.loading));
        VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(arrayReq);

    }

ResponseHelper also you can use on this way.apply your logic :)

Check this for more.

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
0

I use VolleyService in Util app folder as following :

public class VolleyService {

    private static VolleyService instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private VolleyService(Context context) {
        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url,bitmap);
            }
        });
    }

    public static VolleyService getInstance(Context context) {
        if (instance == null) {
            instance = new VolleyService(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

And when I need an instance i just use :

VolleyService.getInstance(context)

Or creating the request :

RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    // we got the response, now our job is to handle it
                    try {
                        updateArticleData(response, syncResult,categoryID);
                    } catch (RemoteException | OperationApplicationException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    //something happened, treat the error.
                    Log.e("Error", error.toString());
                }
            });

            queue.add(request);
Kenan Begić
  • 1,228
  • 11
  • 21