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);
}
我正在尝试确定哪个请求因具有 unique_id 而失败。
我正在使用 unique_id 调用 getTestDats("1") 函数。并且函数调用了 10 次,并且 addToRequestQueue 中的所有 api 调用。
当 API 进入成功部分时,它按照代码工作。
但是当 API 进入错误部分时,我没有识别请求。
有什么方法可以知道我的请求参数,以便我可以使用特定的 unique_id 请求重试。
Best Answer-推荐答案 strong>
在 loginRequest 中设置一个字段,并在 onErrorResponse 中访问该字段,例如 loginRequest.getUniqueId()
或者,创建一个单独的类来实现 Response.Listener 和 ErrorListener
响应监听类:
public class MyReponseListener implements Response.Listener<JSONOBject>{
private long uniqId;
public MyResponseListener(long uniqId){
this.uniqId = uniqId;
}
@Override
public void onResponse(JSONObject response) {
System.out.println("response for uniqId " + uniqId);
// do your other chit chat
}
}
ErrorListener 类:
public class MyErrorListener implements ErrorListener{
private long uniqId;
public MyErrorListener(long uniqId){
this.uniqId = uniqId;
}
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error for uniqId : " + uniqId);
}
}
现在这样调用它:
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new MyResponeListener(uniqId), new MyErrorListener(uniqId));
现在,如果您希望在 ErrorListener 类中可以访问调用类的某些代码,请执行以下操作:
1.在调用类中,将要访问的代码放入方法中
2.用这些方法创建一个接口(interface)
3.调用类将实现该接口(interface)
4. 将接口(interface)传递给 MyErrorListener 或 MyResponseListener 的构造函数
例如, Activity 调用 volley 请求,出错时您想显示一条消息。
将显示错误代码放入方法中:
public void showMessage(int errorCode){
//message according to code
}
现在创建一个界面
public interface errorMessageInterface{
void showMessage(int errorCode);
}
activity 将实现 errorMessageInterface 并将其传递给 MyErrorListener 的构造函数并保存在 field .
在onErrorResponse 里面,你会调用
field.showMessage()
关于Android Volley 请求标识 onErrorResponse 部分,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/38566291/
|