Java 安卓截击可以';不能在单独的类中获取值
并调用Java 安卓截击可以';不能在单独的类中获取值,java,android,json,android-volley,Java,Android,Json,Android Volley,并调用getValue()方法。此方法始终为空,如:“”。有人知道我如何增强我的类以使此代码正常工作吗?此问题不是由于错误的链接或错误的请求造成的。我可以记录响应,这确实有效(当然是在VolleyStringRequest内部)您运行: RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext()); String url= "http://grwn.ddns.net:1337/res
getValue()
方法。此方法始终为空,如:“”。有人知道我如何增强我的类以使此代码正常工作吗?此问题不是由于错误的链接或错误的请求造成的。我可以记录响应,这确实有效(当然是在VolleyStringRequest内部)您运行:
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();
但是请记住,createStringRequest
是异步方法,value
在延迟后填充,例如在public void onResponse(字符串响应)
因此,当您调用volleyStringRequest.getValue()时代码>你得到的是空字符串
要使其正常工作,您可以编写以下界面:
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body);
rq.add(volleyStringRequest.createStringRequest());
volleyStringRequest.getValue();
并将其传递给VolleyStringRequest
构造函数:
public interface RequestHandlerInterface(){
void onResponse(String resp);
}
接下来,更改您的截击字符串请求
:
RequestHandlerInterface rh = this; //Your main class should implement this method
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, rh);
rq.add(volleyStringRequest.createStringRequest());
收到POST的响应后,调用回调,如下所示:
public class VolleyStringRequest {
String url;
String body;
String value;
public VolleyStringRequest(String url, String body, RequestHandlerInterface rh){
this.url = url;
this.body = body;
this.rh = rh;
value= "";
}
//...
}
因此,在底线中调用volleyStringRequest.getValue()代码>
你有:
@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();
if(this.rh != null){
this.rh.onResponse(value);
}
} catch (JSONException ex){}
}
当您收到回复后,将调用该选项,谢谢您再问一个问题。如何将resp from onResponse分配给变量?我好像不明白working@SanderBakker你在用volleyStringRequest.getValue()做什么代码>?分配变量?这在onCreateView中有效吗?对于异步任务,您可以使用Android处理程序更新主线程,但这是另一个问题。
@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();
if(this.rh != null){
this.rh.onResponse(value);
}
} catch (JSONException ex){}
}
@Override
void onResponse(String resp){
// here you go
}