Search code examples
javaandroidserverreturnandroid-volley

Method returns before finished executing?


My java skills are quite good, still I fail to grasp what happens here. I am programming an android app and right now I am programming a class which uses the Google Volley API in order to interact with a web-server. The problem is that I want the class to be called like this:

Server_interaction s_i = new Server_interaction(getApplication);
String text = s_i.post_request();

Text should now contain the returned post request, in my case the string "Hello from server". Instead, it turns out to be null. This happens because the post_request method seems to return before having executed the post_request.

Here is the Server_interaction class:

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;

}

}

When being executed, logcat shows this:

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

So this means that the string is null when being returned, then afterwards it is set. How can this be fixed?

Thanks in advance!


Solution

  • Your code is asynchrounous.

    The StringRequest object created in method post_request() will be used by the framework after the method returns.