Java 方法在完成执行之前返回?
我的java技能相当不错,但我仍然无法理解这里发生了什么。 我正在编写一个android应用程序,现在我正在编写一个类,它使用Google Volley API与web服务器交互。 问题是我希望类的调用方式如下:Java 方法在完成执行之前返回?,java,android,server,return,android-volley,Java,Android,Server,Return,Android Volley,我的java技能相当不错,但我仍然无法理解这里发生了什么。 我正在编写一个android应用程序,现在我正在编写一个类,它使用Google Volley API与web服务器交互。 问题是我希望类的调用方式如下: Server_interaction s_i = new Server_interaction(getApplication); String text = s_i.post_request(); 文本现在应该包含返回的post请求,在我的例子中是字符串“Hello from ser
Server_interaction s_i = new Server_interaction(getApplication);
String text = s_i.post_request();
文本现在应该包含返回的post请求,在我的例子中是字符串“Hello from server”。相反,结果是空的。这是因为post_请求方法似乎在执行post_请求之前返回
以下是服务器交互类:
public class Server_interaction
{
String server_url = "someipadress/greeting.php"; //this address is correct, but I want to hide it for you guys :)
String response_string;
Context myContext;
RequestQueue requestQueue;
public static final String TAG = Server_interaction.class.getSimpleName();
/* Here we add a constructor that takes in context. We need a context for volley requestqueue, and this is an elegant way*/
public Server_interaction(Context context)
{
myContext = context;
requestQueue = Volley.newRequestQueue(myContext);
}
public String post_request()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
response_string = response;
requestQueue.stop();
Log.i(TAG, "the response is: "+ response_string);
}
}
, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
response_string = "Something went wrong";
//error.printstacktrace()
requestQueue.stop();
}
}
); //stringrequest parameter end
//add request to requestqueue
requestQueue.add(stringRequest);
Log.i(TAG, "the response again:: "+ response_string);
return response_string;
}
这意味着返回时字符串为空,然后设置它。如何解决这个问题
提前谢谢 您的代码是异步的
在方法
post\u request()
中创建的StringRequest
对象将在方法返回后由框架使用。您的代码是异步的
在方法
post\u request()
中创建的StringRequest
对象将在方法返回后由框架使用。Aha!如何巧妙地解决这个问题?有什么建议吗?尝试使用Future:不需要Future
,但你必须深入了解你使用的框架。RTFM!啊哈!如何巧妙地解决这个问题?有什么建议吗?尝试使用Future:不需要Future
,但你必须深入了解你使用的框架。RTFM!这是因为请求是异步执行的。当您的请求运行在不同的线程上时,您可以使用接口将响应发送回调用classIt的线程,因为请求是异步执行的。当您的请求运行在不同的线程上时,您可以使用接口将响应发送回调用类
01-22 19:00:44.878 2954-2954/com.example.koenraad.Exigentia I/Server_interaction: the response again:: null
01-22 19:00:44.926 2954-2954/com.example.koenraad.Exigentia I/Server_interaction: the response is: hello from server