How to make serverAnswer transmitted outside onResponse?

And it turns out that the data is put into serverAnswer in onResponse, but outside of onResponse the serverAnswer variable is empty.

Suppose if you output Toast with serverAnswer in onResponse, then the required text is displayed, and if, say, output Toast outside onResponse, then emptiness is displayed.

And addUser passes an empty string.

public String addUser(final String username, final String email, final String password, final Context context) { StringRequest request = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() { @Override public void onResponse(final String response) { try { JSONObject jsonObject = new JSONObject(response); final JSONObject status = jsonObject.getJSONObject("Result"); serverAnswer = status.getString("Server answer"); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { serverAnswer = error.getMessage(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put(KEY_USERNAME, username); params.put(KEY_EMAIL, email); params.put(KEY_PASSWORD, password); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(context); requestQueue.add(request); return serverAnswer; } 

1 answer 1

You have an asynchronous request, so everywhere on the code, until the execution of the request, serverAnswer will be empty. The addUser(...) method returns the value before the response came from the server.

I will offer a couple of options:

  1. In the addUser(...) method addUser(...) can pass a callback:

     public interface OnRequestFinishedListener { void onResponse(String serverAnswer); } 

     public void addUser(..., OnRequestFinishedListener onRequestFinishedListener) { ... } 

    and after the server’s response, call the appropriate method:

     onRequestFinishedListener.onResponse(serverAnswer); 
  2. You can execute the query synchronously , but then you have to mess around with creating the background thread in which the method will run.

  • onRequestFinishedListener.onResponse (serverAnswer); And then in this method and transfer serverAnswer? return ServerAnswer - Pavel.jeckit