0
public class VolleyStringRequest {
String url;
String body;
String value;
public VolleyStringRequest(String url, String body){
this.url = url;
this.body = body;
value= "";
}
public StringRequest createStringRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
Log.e("Response", response);
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("response");
value += values.toString();
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
return body.getBytes();
};
@Override
public String getBodyContentType() {
return "application/json";
}
};
return stringRequest;
}
public String getValue() {
return value;
}
}
我在一个单独的类写了这个代码,以防止重复的代码,但是当我运行这个像这样的片段中:Android的凌空不能在单独的类中获得价值
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://grwn.ddns.net:1337/results";
final String body = "{\"id\":1}";
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body);
rq.add(volleyStringRequest.createStringRequest());
volleyStringRequest.getValue();
,并调用getValue()
方法。此方法始终为空:“”。有谁知道我可以如何提高我的课程,这样的代码将工作?这个问题并不是因为错误的链接或错误的请求。我可以登录响应,并且不工作(ofcourse内VolleyStringRequest)
再次感谢您的问题。我如何将onResponse的resp分配给一个可变的值?我似乎无法得到它的工作 –
@SanderBakker你在用'volleyStringRequest.getValue();'做什么? –
分配变量?这将工作在onCreateView? –