本文介绍了android volley最终有回调做类似java的事情吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请求完成后,我必须做点什么.就像关闭加载对话框一样
I have to do something after the request finish. like dismiss a loading dialog
在onResponse()和onErrorResponse()的每个请求中,我都必须添加dialog.dismiss();
.
I have to add dialog.dismiss();
in every request for both onResponse() and onErrorResponse().
齐射有全局回调吗?我想在相同的片段/活动中使用全局回调,以处理错误/成功的消息
Do volley have global callback? I want to have global callback in same fragment/activity to handle error/successful message
JsonRequest jsonRequest = new JsonRequest
(url, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
dialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
}
}) {
};
推荐答案
是的,您可以通过创建自定义截击请求来做到这一点.参见下面的代码:
Yes you can do this by creating custom volley request.See the code below :
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import android.app.AlertDialog;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
private AlertDialog dialog;
//You can replace AlertDialog by the Type of dialog you use
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener,AlertDialog dialog)
{
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.dialog =dialog;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
//Here you can call dialog.dismiss();
dialog.dismiss();
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
}
让我知道这是否可行. :)
Let me know if this works. :)
这篇关于android volley最终有回调做类似java的事情吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!