android-需要Volley API调用简化的解决方案,从一个方法调用所有API

android-需要Volley API调用简化的解决方案,从一个方法调用所有API,第1张

概述这是一个简单的VolleyApi侦听器,如何从单个Api调用方法中调用项目中的每个API.我在一个项目中有大约40个其他类似的API,我厌倦了一次又一次地编写相同的代码块.有谁知道如何做到这一点?==>我听说使回调是一种解决方案,但我想要处理它的确切方法.privatevoidreservationCance

这是一个简单的Volley API侦听器,如何从单个API调用方法中调用项目中的每个API.我在一个项目中有大约40个其他类似的API,我厌倦了一次又一次地编写相同的代码块.有谁知道如何做到这一点?
==>我听说使回调是一种解决方案,但我想要处理它的确切方法.

  private voID reservationCancelAPIExecute(String reservation_ID) {        CustomProgressbarDialog.progressDialog = CustomProgressbarDialog.showProgressDialog(mcontext);        if (visible) CustomProgressbarDialog.progressDialog.show();        final HashMap<String, String> params = new HashMap<>();        params.put("user_ID", user_ID);        params.put("reservation_ID", reservation_ID);        Log.e("Parameters", params.toString());        String REquestUrl = Config.APP_BASE_URL + Config.API_RESERVATION_CANCEL;        StringRequest req = new StringRequest(Request.Method.POST, REquestUrl,                new Response.Listener<String>() {                    @OverrIDe                    public voID onResponse(String responSEObject) {                        String newResponse = responSEObject;                        CustomProgressbarDialog.progressDialog.dismiss();                        if (responSEObject.contains("")) {                            newResponse = newResponse.substring(newResponse.indexOf("{"));                        }                        try {                            JsONObject response = new JsONObject(newResponse);                            boolean error = response.getBoolean("error");                            if (!error) {                                CustomProgressbarDialog.progressDialog.dismiss();                                session.createReservationByUser(DBtableFIElds.RESERVATION_STATE_CANCELLED);                                session.createReservationByUser(DBtableFIElds.RESERVATION_STATE_NEW);                                //EApplication.getInstance().showToastMessageFunction(response.getString("message"));                               /* session.clearPickUPDropOffLocationAddress();*/                                EApplication.getInstance().setPrevIoUsReservationStatus(false);                               /* reservationCancelSuccessDialog();*/                                if (isAdded()) {                                    EApplication.getInstance().showToastMessageFunction(getResources().getString(R.string.canceled_reservation));                                }                                //Toast.makeText(mcontext, getResources().getString(R.string.canceled), Toast.LENGTH_SHORT).show();                            } else                            {                                EApplication.getInstance().showToastMessageFunction("" + response.getString("message"));                                CustomProgressbarDialog.progressDialog.dismiss();                            }                        } catch (JsONException e) {                            e.printstacktrace();                            CustomProgressbarDialog.progressDialog.dismiss();                        }                    }                }, new Response.ErrorListener() {            @OverrIDe            public voID one rrorResponse(VolleyError error) {                if(isAdded())                EApplication.getInstance().showToastMessageFunction(getResources().getString(R.string.no_internet_availeble));                VolleyLog.d("Error", "Error: " + error.getMessage());                CustomProgressbarDialog.progressDialog.dismiss();            }        }) {            @OverrIDe            protected Map<String, String> getParams() throws AuthFailureError {                return params;            }            @OverrIDe            public Request.Priority getPriority() {                return Request.Priority.HIGH;            }            @OverrIDe            public Map<String, String> getheaders() throws AuthFailureError {                HashMap<String, String> headers = new HashMap<String, String>();                            /*headers.put("Content-Type", "application/Json");*/                String current_language = session.getAppLanguage();                Log.i("current_language", current_language);                if (current_language.equalsIgnoreCase(Config.LANG_ENG)) {                    language = "en";                }                if (current_language.equalsIgnoreCase(Config.LANG_THAI)) {                    language = "np";                }                headers.put("lang", language);                return headers;            }        };        req.setRetryPolicy(new DefaultRetryPolicy(                20000,                DefaultRetryPolicy.DEFAulT_MAX_RETRIES,                DefaultRetryPolicy.DEFAulT_BACKOFF_MulT));        EApplication.getInstance().addToRequestQueue(req, "high");    }

由Config文件组成,即API列表

package com.EddyCablatest.application.constant;public class Config {    public static final String PRIVACY_POliCY_DRIVER_NEPAli =            "<a href=https://www.eddycab.com/np/legal-2/privacy/drivers/";    public static final String PRIVACY_POliCY_DRIVER_ENGliSH =            "<a href=https://www.eddycab.com/en/legal/privacy/drivers/";    public static final String PRIVACY_POliCY_PASSENGER_ENGliSH = "<a href=https://www.eddycab.com/en/legal/privacy/users/";    public static final String PRIVACY_POliCY_PASSENGER_NEPAli =            "<a href=https://www.eddycab.com/np/legal-2/privacy/users/";    public static final String TERMS_DRIVER_NEPAli =            "<a href=https://www.eddycab.com/np/legal-2/user-terms/";    public static final String TERMS_DRIVER_ENGliSH =            "<a href=https://www.eddycab.com/en/legal/terms-conditions/";    public static final String Google_MAP_API_KEY = "AIzaSyAi6qreeIcyoDDxtrcMnYqKwTMR064C4xc";//test    public static final String GCM_SENDER_KEY = "1024195933443";    public static final String APP_BASE_URL = "https://www.eddycab.com/API/public/";    public static final String USER_REGISTER_URL = "API/users/register";    public static final String USER_LOGIN_URL = "API/users/login";    public static final String CREDIT_BONUS = "API/bananas/credit-and-bonus/";    public static final String GET_NEW_RESERVATIONS = "API/reservations/new-reservations-by-driver/";    public static final String USER_SET_BOOKING_URL = "API/reservations/set-booking";    public static final String USER_GET_DRIVER_LOCATION_POST_URL = "API/reservations/get-driver-location";    public static final String GET_BIDDING_RESulT_URL = "API/reservations/bIDdings/";    public static final String GET_USER_PROfile = "API/users/get-user-profile/";    public static final String USER_RESERVATION_URL = "API/reservations/create";    public static final String API_RESERVATION_CANCEL = "API/reservations/cancel-reservation/";    public static final String USER_RESERVATION_RESPONSE_URL = "API/reservations/bIDdings/";    public static final String UPDATE_FAV_HOME_URL = "API/users/set-favourite-home-place";    public static final String UPDATE_FAV_WORK_URL = "API/users/set-favourite-work-place";    public static final String EDIT_PROfile = "API/users/edit-profile";    public static final String UPDATE_USER_PROfile_CHANGE_PROfile_PIC = "API/users/set-profile-picture";    public static final String DRIVER_BID_POST = "API/reservations/driverPostBID";    public static final String DRIVER_RESERVATION_ASSIGN_POST = "API/reservations/reservation-assign";    public static final String DRIVER_RESERVATION_IGnorE_POST = "API/reservations/reservation-ignore";    public static final String DRIVER_RESERVATION_CANCEL_POST = "API/reservations/cancel-reservation-by-driver";    public static final String DRIVER_DRIVER_PICKUP_PASSENGER_POST = "API/reservations/pickup-passenger";    public static final String API_BIDDER_CANCEL_BY_USER = "API/reservations/cancel-bIDder";    public static final String USER_TRIP_HISTORY_URL = "API/reservations/user-trip-history/";    public static final String Driver_BOOKING_HISTORY_URL = "API/reservations/driver-booking-history/";    public static final String NEAREST_DRIVER_BY_LOCATION = "API/reservations/get-nearest-drivers";    public static final String DRIVER_GET_QUITE_TIME_URL = "API/quIEtsetting/get-quIEt-setting/";    public static final String DRIVER_SET_QUITE_TIME_URL = "API/quIEtsetting/set-quIEt-setting";    public static final String SET_USER_LOCATION_POST_URL = "API/locations/set-location";    public static final String GET_PUSH_NOTIFICATION_DRIVER = "API/reservations/send-reservation-push-notifications/";    public static final String USER_FeedBACK_rating_URL = "API/Feedbacks/user-feedback";    public static final String SUPPORT_FeedBACK_POST_URL = "API/support/insert-Feedback";    public static final String GET_MESSAGES_FROM_GCM_URL = "API/notifications/get-all-notifications/";    public static final String DRIVER_JOB_COMPLETE_URL = "API/reservations/reservation-complete";    public static final String DRIVER_PAY_VOUCHER_URL = "API/reservations/reservation-receipt";    public static final String DELETE_NOTIFICATION_MESSAGE = "API/notifications/remove-message/";    public static final String DELETE_ALL_NOTIFICATION_MESSAGE = "API/notifications/remove-user-messages/";    public static final String USER_logoUT = "API/users/logout/";    public static final String CHANGE_LANGUAGE = "API/users/set-language";    public static final String LANG_ENG = "English";    public static final String LANG_THAI = "Thai";    public static final String USER_TYPE_DRIVER = "driver";    public static final String USER_TYPE_USER = "user";    public static final String USER_TYPE_USER_ID = "1";    public static final String CALL_CENTER_NUMBER = "16600177711";    public static final String Driver_TYPE_USER_ID = "2";    public static final float CAMERA_FACTORY_UPDATE = 15;    public static final String DEVICE_TYPE = "androID";    public static final long COUNTDOWN_TIME = 30000;    public static final String FORGET_PASSWORD_SEND_MESSAGE = "API/users/forget-password/";    public static final String CONFIRM_VERIFICATION_CODE = "API/users/verify-code";    public static final String API_SET_NEW_PASSWORD = "API/users/set-new-password";    public static final String RATE_USER_BY_DRIVER = "API/Feedbacks/driver-Feedback";    public static final String URL_RESEEND_CODE_GET = "API/users/resend-code/";    public static final String DRIVER_RECHARGE_HISTORY = "API/bananas/recharge-card-history/";    public static final String RECHARGE_CARD = "API/bananas/recharge-card/";    public static String DRIVER_JOB_COMPLETE_URL_call_center = "API/reservations/complete-callcenter-created-reservation";}

解决方法:

您可以尝试以下方法:

创建自己的自定义接口以获取回调:

import org.Json.JsONObject;/** * Implement this Listener for getting callback for UploadManager.doUpload() * method. *  *  */public interface UploadListener {    /**     * On success upload, server response for given network upload task.     *      * @param response     */    voID onSuccessuploadResponse(JsONObject response);    /**     * On Failed upload, server response for given network upload task.     *      * @param error     */    voID one rrorUploadResponse(Throwable error);}

比为网络 *** 作创建一个Singleton类并抽象出凌空代码:

import org.Json.JsONObject;import androID.content.Context;import androID.util.Log;import com.androID.volley.Request;import com.androID.volley.RequestQueue;import com.androID.volley.Response;import com.androID.volley.VolleyError;import com.androID.volley.toolBox.JsonObjectRequest;import com.androID.volley.toolBox.Volley;/** * Singleton class for network operations and to abstract out the volley * code. *  * @see <a *      href=" http://developer.androID.com/training/volley/index.HTML">Volley</a> *  *  */public class UploadManager {    private static UploadManager uploadManager;    private static RequestQueue mRequestQueue;    public static final int METHOD_POST = Request.Method.POST;    public static final int METHOD_GET = Request.Method.GET;    public static final int METHOD_PUT = Request.Method.PUT;    public static final int METHOD_DELETE = Request.Method.DELETE;    private UploadManager(Context context) {        mRequestQueue = Volley.newRequestQueue(context);        // Start the queue        mRequestQueue.start();    }    public static UploadManager getinstance(Context context) {        if (uploadManager == null) {            uploadManager = new UploadManager(context);        }        return uploadManager;    }    /**     * Implement UploadManager.CallbackListener for getting callback for this     * method.     *      * @param url     *            : url to be used for network call.     * @param method     *            : http method type.     * @param JsonRequest     *            : JsON object to be sent     * @param callbackListener     *            : callback Listener for getting success or error callback.     */    public voID doUpload(String url, int method, JsONObject JsonRequest,            final UploadListener callbackListener) {        JsonObjectRequest JsObjRequest = new JsonObjectRequest(method, url,                JsonRequest, new Response.Listener<JsONObject>() {                    public voID onResponse(JsONObject response) {                        callbackListener.onSuccessuploadResponse(response);                    };                }, new Response.ErrorListener() {                    @OverrIDe                    public voID one rrorResponse(VolleyError error) {                        if (null != error) {                            callbackListener.onErrorUploadResponse(error                                    .getCause());                        }                    }                });        mRequestQueue.add(JsObjRequest);    }}

您可以使用doUpload();您所有类中的方法,而无需一次又一次地编写volley代码.

总结

以上是内存溢出为你收集整理的android-需要Volley API调用简化的解决方案,从一个方法调用所有API全部内容,希望文章能够帮你解决android-需要Volley API调用简化的解决方案,从一个方法调用所有API所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1090804.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存