public void getTestDats(String unique_id) { final String tag = "testList"; String url = Constants.BASE_URL + "test_module.php"; Map<String, String> params = new HashMap<String, String>(); params.put("user_id", SharedPreferenceUtil.getString(Constants.PrefKeys.PREF_USER_ID, "1")); params.put("unique_id", unique_id);//1,2,3,4,5 DataRequest loginRequest = new DataRequest(Method.POST, url, params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { switch (response.optInt("unique_id")) { case 1: //task 1 break; case 2: //task 2 break; default: //nothing } } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //I want to know which unique_id request is failed } }); loginRequest.setRetryPolicy(new DefaultRetryPolicy(20000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); AppController.getInstance().addToRequestQueue(loginRequest, tag); } I'm trying to identity which request is failed with having unique_id.I'm calling getTestDats("1") function with unique_id. And function called 10 times and all the api call in addToRequestQueue. When API go into Success part its working as per code. But when API go into Error part I didn't identity the request. Is there any way to know my request param so I can retry with particular unique_id request.
7 Réponses :
Ajoutez simplement ce code pour identifier le type d'erreur que vous êtes confronté.Ajouter cela dans votre méthode Onerror ():
if (error instanceof TimeoutError) { Log.e(TAG, "TimeoutError"); } else if (error instanceof NoConnectionError) { Log.e(TAG,"tNoConnectionError"); } else if (error instanceof AuthFailureError) { Log.e(TAG,"AuthFailureError"); } else if (error instanceof ServerError) { Log.e(TAG,"ServerError"); } else if (error instanceof NetworkError) { Log.e(TAG,"NetworkError"); } else if (error instanceof ParseError) { Log.e(TAG,"ParseError"); }
enregistre le unique_id code> avant de faire une demande, c'est-à-dire; Après
parames.put ("unique_id", unique_id); // 1,2,3,4,5 code>. Et une fois que vous avez reçu la réponse dans
OnResponse () Code> méthode. Et croix vérifier ce qui se passe exactement. P>
réglé dans un champ En variante, créer une classe individuelle qui implémente Response.Listener et ErrorListener p> Réponse classe Listener: p> loginRequest code> et
onErrorResponse code> accéder au champ comme
loginRequest.getUniqueId () code>
field.showMessage()
Vous pouvez analyser la réponse d'erreur de la même manière que vous analysez la réponse du succès. J'utilise une solution similaire dans mes projets.
... , new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { int id = new VolleyErrorParse(error).getUniqueId(); switch (id) { case -1: //unique id not found in the answer break; case 1: //task 1 break; case 2: //task 2 break; default: //nothing } } } ...
La plupart des solutions ici "travailleront" mais elles sont trop complexes .. pour moi :) Voici l'option la plus simple avec le moindre changement de code, je peux penser:
... final Map<String, String> params = new HashMap<String, String>(); params.put("user_id", SharedPreferenceUtil.getString(Constants.PrefKeys.PREF_USER_ID, "1")); params.put("unique_id", unique_id);//1,2,3,4,5 DataRequest loginRequest = new DataRequest(Method.POST, url, params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { switch (params.get("unique_id")) { case 1: //task 1 break; case 2: //task 2 break; default: //nothing } } ...
Toutes les réponses ci-dessus semblent être correctes. Mais je vous recommande de le faire de manière optimisée. Si vous allez ajouter un code de traitement des erreurs dans tous les onerrorresponse () code>, il créera une duplication. Donc, créez une méthode de
séparée code> dans
utils code> ou d'autre
class code> et appelez simplement que
méthode code> en passant
Erreur Objet code> à la méthode
code>. Aussi, vous pouvez gonfler une boîte de dialogue code> ou
toast code> pour afficher un message d'erreur
code>.
public static void handleError(final Context context, String alertTitle,
Exception exception, String logTag) {
if (context != null) {
if (exception instanceof TimeoutError)
message = context.getString(R.string.TimeoutError);
else if (exception instanceof NoConnectionError)
message = context.getString(R.string.NoConnectionError);
else if (exception instanceof AuthFailureError)
message = context.getString(R.string.AuthFailureError);
else if (exception instanceof ServerError)
message = context.getString(R.string.ServerError);
else if (exception instanceof NetworkError)
message = context.getString(R.string.NetworkError);
else if (exception instanceof ParseError)
message = context.getString(R.string.ParseError);
message = exception.getMessage();
DialogHelper.showCustomAlertDialog(context, null,
alertTitle, message, "ok",
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
}, null, null);
}
}
Je pense que vous devez faire une méthode de conman sur la classe de base. Comme indiqué ci-dessous que j'ai utilisé dans mon code pour appeler PHP Web API
/** * <h1> Use for calling volley webService </h1> * * @param cContext Context of activity from where you call the webService * @param mMethodType Should be POST or GET * @param mMethodname Name of the method you want to call * @param URL Url of your webService * @param mMap Key Values pairs * @param initialTimeoutMs Timeout of webService in milliseconds * @param shouldCache Web Api response are stored in catch(true) or not(false) * @param maxNumRetries maximum number in integer for retries to execute webService * @param isCancelable set true if you set cancel progressDialog by user event * @param aActivity pass your activity object */ public void callVolley(final Context cContext, String mMethodType, final String mMethodname, String URL, final HashMap<String, String> mMap, int initialTimeoutMs, boolean shouldCache, int maxNumRetries, Boolean isProgressDailogEnable, Boolean isCancelable, final Activity aActivity) { mMap.put("version_key_android",BuildConfig.VERSION_NAME+""); if (!isOnline(cContext)) { //showErrorDailog(aActivity, Constant.PleaseCheckInternetConnection, R.drawable.icon); } else { StringRequest jsObjRequest; int reqType = 0; String RequestURL = URL.trim(); queue = Volley.newRequestQueue(cContext); if (isProgressDailogEnable) { customLoaderDialog = new CustomLoaderDialog(cContext); customLoaderDialog.show(isCancelable); customLoaderDialog.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // finish(); } }); } if (mMethodType.trim().equalsIgnoreCase("GET")) reqType = com.android.volley.Request.Method.GET; else if (mMethodType.trim().equalsIgnoreCase("POST")) reqType = com.android.volley.Request.Method.POST; if (RequestURL.equals("")) RequestURL = Constant.BASE_URL; else RequestURL = URL; if (Constant.d) Log.d("reqType", reqType + ""); jsObjRequest = new StringRequest(reqType, RequestURL, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { if (Constant.d) Log.d("response==>" + mMethodname, "" + response); if (customLoaderDialog != null) { try { customLoaderDialog.hide(); } catch (Exception e) { e.printStackTrace(); } } if (response == null || response.length() == 0) { IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity; iVolleyRespose.onVolleyResponse(404, response, mMethodname); } else { JSONObject json_str; try { json_str = new JSONObject(response); int status = json_str.getInt("status"); if (status == 100) { AlertDialog alertDialog = new AlertDialog.Builder(aActivity).create(); alertDialog.setTitle(getResources().getString(R.string.app_name)); alertDialog.setMessage(json_str.getString("message") + ""); alertDialog.setCancelable(false); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(Constant.playStoreUrl)); startActivity(viewIntent); }catch(Exception e) { Toast.makeText(getApplicationContext(),"Unable to Connect Try Again...", Toast.LENGTH_LONG).show(); e.printStackTrace(); } dialog.dismiss(); // return; } }); alertDialog.show(); } else { IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity; iVolleyRespose.onVolleyResponse(RESPONSE_OK, response, mMethodname); } } catch (Exception e) { e.printStackTrace(); } } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { // TODO Auto-generated method stub IVolleyRespose iVolleyError = (IVolleyRespose) aActivity; iVolleyError.onVolleyError(404, "Error", mMethodname); if (customLoaderDialog != null) { customLoaderDialog.hide(); } } }) { @Override protected Map<String, String> getParams() { String strRequest = ""; try { strRequest = getWebservicejsObjRequestforvolley(mMethodname, mMap); if (Constant.d) Log.d("Request==>", strRequest + ""); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String, String> params = new HashMap<>(); params.put("json", strRequest); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Content-Type", "application/x-www-form-urlencoded"); return params; } }; //if(Constant.d) Log.d("Request==>", jsObjRequest+""); jsObjRequest.setTag(mMethodname); jsObjRequest.setShouldCache(shouldCache); jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(initialTimeoutMs, maxNumRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); queue.add(jsObjRequest); } }
Lorsque vous appelez la demande, à cette époque Store ID unique dans une variable globale, puis sur l'erreur, vous pouvez facilement l'utiliser.