【发布时间】:2015-03-26 04:28:57
【问题描述】:
您好,我想将 volley 请求模块化,这样我就不会将活动演示代码与 volley 请求混合在一起。 我看到的所有示例,凌空请求都被放置在 - 例如 - 来自活动按钮的 OnClick 事件上。
我的意思是这段代码(取自差异源):
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
我的意思是如何将所有请求代码传递给另一个类,然后实例化该类并调用 makeRequest。 我已经尝试过了,但它失败了。我不知道它是否与上下文相关,但它失败了......
我这样做了:
public void onClick(View v) {
try{
Utils varRequest = new Utils(getApplicationContext());
String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
varRequest.makeRequest(url);
mitexto.setText(varRequest.miError);
}
catch(Exception excepcion) {
System.out.println(excepcion.toString());
}
}
... 而 Utils 类是:
public class Utils {
public Context contexto;
public String miError;
private RequestQueue queue ;
public Utils (Context contextoInstancia){
contexto = contextoInstancia;
queue = Volley.newRequestQueue(contexto);
}
public void makeRequest(String url){
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
miError="Response => "+response.toString();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
miError="Response => "+error.networkResponse.toString();
}
});
queue.add(jsObjRequest);
}
}
谁能告诉我我做错了什么,或者如何构造代码?
提前致谢。
【问题讨论】:
-
异步是异步的 ... mitexto.setText(varRequest.miError);应该在 onResponse 或 onErrorResponse 中调用...或者具有 onClick 的类应该实现 Response.Listener ...
-
呵呵呵呵,所以
Response.Listener<T>他应该改用CallBack<T>?区别在哪里? -
我认为 Rohit Patil 在stackoverflow.com/questions/35628142/… 中的回答是您想要的。