Xin chào, tôi muốn môđun hóa các yêu cầu bóng chuyền vì vậy tôi không trộn mã trình diễn hoạt động với các yêu cầu volley. Tất cả các mẫu tôi đã thấy, yêu cầu bóng chuyền đang được đặt - ví dụ- trên sự kiện OnClick từ nút hoạt động.Android Volley - Cách tách biệt các yêu cầu trong một lớp học khác
Ý tôi là mã này (lấy từ nguồn khác):
// 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);
Quan điểm của tôi ở đây là làm thế nào để có được điều này mã tất cả yêu cầu đến một lớp học và chỉ dụ lớp và gọi makeRequest. Tôi đã thử điều này nhưng không thành công. Tôi không biết nếu đó là một cái gì đó liên quan với bối cảnh nhưng nó không thành công ...
Tôi đã làm điều này:
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());
}
}
... và lớp Utils là:
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 bất cứ ai cho tôi biết những gì tôi đang làm sai, hoặc làm thế nào để cấu trúc mã?
Xin cảm ơn trước.
async là async ... mitexto.setText (varRequest.miError); nên được gọi trong onResponse hoặc onErrorResponse ... hoặc lớp học có onClick nên triển khai Response.Listener ... – Selvin
hehehe, vì vậy thay vào đó 'Response.Listener' anh ấy nên sử dụng 'CallBack '? sự khác biệt ở đâu? –
Selvin
Tôi nghĩ câu trả lời của Rohit Patil trong http://stackoverflow.com/questions/35628142/how-to-make-separate-class-for-volley-library-and-call-all-method-of-volley-from là một trong những bạn muốn. – SajithK