我是Android的新手,希望您对StringRequestVolley有帮助。在我的项目中,我将调用几个API。为此,我创建了一个名为ProcessAPIRequest的方法。为此,我将传递URL作为参数。这是我的函数代码片段。
hell<
我面临的问题是,每当我调用此方法时,我都会得到空响应。返回响应后,将触发public void onResponse方法。我希望响应一旦得到结果就应该返回。
答案 0 :(得分:1)
您将为此使用回调接口。这是一个例子。
public interface OnResponse{
void onResponse(String response);
}
public static void ProcessAPIRequest(String pURL, Context pContext, final OnResponse onResponse){
StringRequest stringRequest = new StringRequest(pURL,
new Response.Listener<String>() {
@Override
public void onResponse(String strResponse) {
onResponse.onResponse(strResponse); // callback for success
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error.networkResponse;
//Log.e("error", "" + error);
onResponse.onResponse(null); // callback for error
}
});
RequestQueue requestQueue = Volley.newRequestQueue(pContext);
requestQueue.add(stringRequest);
}
答案 1 :(得分:1)
问题在于VolleyRequests在异步线程上运行,实现它的正确方法是一旦获得响应就进行回调。
创建界面
public interface VolleyResultCallBack {
void onVolleyResultListener(String response, String requestUrl);
void onVolleyErrorListener(VolleyError error,String requestUrl);
}
和您的方法
public static void ProcessAPIRequest(VolleyResultCallBack resultListener,String pURL, Context pContext){
iResponse="";
StringRequest stringRequest = new StringRequest(pURL,
new Response.Listener<String>() {
@Override
public void onResponse(String strResponse) {
resultListener.onVolleyResultListener(strResponse,pURL);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error.networkResponse;
//Log.e("error", "" + error);
resultListener.onVolleyErrorListener(error,pURL);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(pContext);
requestQueue.add(stringRequest);
}
您的班级:-
public class TestActivity extends AppCompatActivity implements VolleyResultCallBack {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ClassName.ProcessAPIRequest(this,"Your URl",this)
}
@Override
public void onVolleyResultListener(String response, String requestUrl) {
if(requestUrl.equals("Your URl"){
//do some thing with response
}
}
@Override
public void onVolleyErrorListener(VolleyError error,String requestUrl) {
// error occured get error and show it
}
}
答案 2 :(得分:0)
您需要添加请求方法GET或POST
StringRequest stringRequest = new StringRequest(Request.Method.GET,pURL,
new Response.Listener<String>() {