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? –