Hi I'd like to modularize the volley requests so I don't mix activity presentation code with volley requests. All samples I saw, the volley request are being placed -for example- on the OnClick event from an activity button.
I mean this code(taken from diff source):
// 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);
My point here is how to get this all request code to another class and just instance the class and call the makeRequest. I already tried this but it fails. I don't know if it's something related with the Context but it fails...
I did this:
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());
}
}
... and the Utils class is:
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);
}
}
Can anyone tell me what I'm doing wrong, or how to structure the code?
Thanks in advance.
Response.Listener<T>
he should useCallBack<T>
? where is a difference? – Havre