我正在为我的大学开设一个项目。我的Android应用程序需要与服务器通信以发送命令并接收一些数据。我能够发送和接收数据。问题是当我想要将数据打印出volly类时,没有可用的接收数据。
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url += "/?data="+ enteredUsername.getText().toString()+","+ enteredPassword.getText().toString()+","+enteredSiteId.getText().toString(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
returnFromServer =response.toString();
requestQueue.stop();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
commandStatus.setText("SERVER DOWN");
error.printStackTrace();
requestQueue.stop();
}
});
requestQueue.add(stringRequest);
commandStatus.setText(returnFromServer);//there is no value here out side the volly class
}
我必须比较返回值表单服务器以供进一步使用。
答案 0 :(得分:1)
在您的类中创建一个ResponseListener对象,如下所示:
Response.Listener<String> response = new Response.Listener<String>(){
@Override
public void onResponse(String response) {
returnFromServer =response.toString();
requestQueue.stop();
}
};
然后将听众传递给凌空:
public void yourMethod(){
....
callApi(response)
....
}
public void callAPI(Response.Listener<String> response) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url += "/?data="+ enteredUsername.getText().toString()+","+ enteredPassword.getText().toString()+","+enteredSiteId.getText().toString(),
response,
new Response.ErrorListener(){...}
}
<强>实施强>
public class MainActivity extends Activity{
Response.Listener<String> response = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
returnFromServer =response.toString();
requestQueue.stop();
}
};
private void callAPI(Response.Listener<String> respone) {
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url += "/?data="+ enteredUsername.getText().toString()+","+ enteredPassword.getText().toString()+","+enteredSiteId.getText().toString(),
response,
, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
commandStatus.setText("SERVER DOWN");
error.printStackTrace();
requestQueue.stop();
}
});
requestQueue.add(stringRequest);
commandStatus.setText(returnFromServer);//there is no value here out side the volly class
}
}
}
只需在任何地方调用callAPI方法,并将响应作为参数传递。如果从服务器收到响应,则在MainActivity中调用onResponse方法。
this
的另一种简单方法。