这是一个简单的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 onErrorResponse(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";
}
答案 0 :(得分:2)
您可以尝试以下方法:
创建自己的自定义界面以获取回调:
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 onErrorUploadResponse(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 onErrorResponse(VolleyError error) {
if (null != error) {
callbackListener.onErrorUploadResponse(error
.getCause());
}
}
});
mRequestQueue.add(jsObjRequest);
}
}
您可以在所有课程中使用doUpload();
方法,而无需一次又一次地编写凌空代码。
答案 1 :(得分:2)
请参阅此https://github.com/gauravpolekar/androidnetworkmodule
您可以使用单一方法,也可以使用requestCode
轻松调用并区分单个类中的多个调用。