如何在android中为volley库创建公共类

时间:2015-11-25 09:54:49

标签: android android-activity

我想为volley库创建一个基类,并希望在Activity上访问响应和Error,我调用了volley请求。因此我的代码将会优化。

2 个答案:

答案 0 :(得分:0)

我个人使用以下类来处理凌空。你可以根据要求恢复它。

排球请求队列助手:

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);
        }
    }
}

理想情况下,您的队列应该有一个集中位置,初始化队列的最佳位置是Application类。上面的片段解释了如何做到这一点

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);
        }

    }


}

内线齐射onErrorResponse

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

为了更清楚地了解使用情况,我发布了我的代码,将其恢复为您的要求

 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也可以这样使用。应用你的逻辑:)

点击this了解详情。

答案 1 :(得分:0)

我在Util app文件夹中使用VolleyService如下:

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;
    }
}

当我需要一个实例时,我只需使用:

VolleyService.getInstance(context)

或创建请求:

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);