1

Im trying to use Volley library and a AsyncTask to conect my app to a local server. But, as you can see in the photos posted below the onPostExecute() method is called before the doInBackground() method ends and I don't know why. The server conection is well done, I tested it.

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button button;
TextView textView, textView2;

WSPOSTconBody wsposTconBody;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    textView = (TextView) findViewById(R.id.text);
    textView2 = (TextView) findViewById(R.id.textView);



    try {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        textView2.setText(String.valueOf(isConnected));
    }catch (NullPointerException e){
        textView2.setText("NullpointerException");
    }

    wsposTconBody = new WSPOSTconBody(MainActivity.this, new OnResponsePOSTconBody() {
        @Override
        public void onSuccess(String response) {
            textView.setText(response);
        }

        @Override
        public void onFailure(Exception exception) {
            if (exception != null){
                textView.setText(exception.toString());
            }
        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v.getId() == R.id.button){
                wsposTconBody.execute("Eder", "Villar");
            }
        }
    });

}

WSPOSTconBody.java

public class WSPOSTconBody extends AsyncTask<String, Void, String>{

private Context applicationContext;

private String USERNAME;
private String PASSWORD;
private String url;

private String respuesta;
private Exception exception;

private OnResponsePOSTconBody onResponsePOSTconBody;

public WSPOSTconBody(Context context, OnResponsePOSTconBody callback){

    USERNAME = "admin";
    PASSWORD = "xyzyx";

    url = "http://localhost:8081/persona/hola";

    applicationContext = context;
    onResponsePOSTconBody = callback;
}

@Override
protected String doInBackground(String... params) {

    try {

        RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("firstname", params[0]);
        jsonBody.put("lastname", params[1]);
        final String requestBody = jsonBody.toString();

        /* ******************* */
        StringRequest objectRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        respuesta = response.toString();
                        Log.d("Respuesta", response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        exception = error;
                        Log.d("Excepcion web", error.toString());

                    }
                }

        ) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() {
                try {
                    return (requestBody.getBytes("utf-8"));
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();

                String credentials = USERNAME + ":" + PASSWORD;
                String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
                headers.put("Authorization", auth);
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
        };
        /* ******************* */

        requestQueue.add(objectRequest);

    }catch (JSONException e){
        e.printStackTrace();
    }

    return respuesta;
}

@Override
protected void onPostExecute(String respuesta) {
    if (onResponsePOSTconBody != null) {
        Log.d("RESPUESTA", "INTERFAZ FUNCIONA");
        if (exception == null) {
            onResponsePOSTconBody.onSuccess(respuesta);
        } else {
            onResponsePOSTconBody.onFailure(exception);
        }
    }
    else {
        Log.d("RESPUESTA", "FALLO LA INTERFACE");
    }
}
}

And the interface - OnResponsePOSTconBody.java

public interface OnResponsePOSTconBody {

void onSuccess(String response);
void onFailure(Exception exception);

}

And here is what the console shows when I press the button

As you can see, D/RESPUESTA: INTERFAZ FUNCIONA is on onPostExecute() method and D/Respuesta: Hola Eder Villar! is on doInBackground() method that is called before the other method

Maybe I need to wait to the server response, stoping the doInBackground() method until that, but i dont know how to do that.

THX

ProRiderZ115
  • 115
  • 2
  • 9
  • Volley handles threading for you. There's no need for an async task – Gabe Sechan Jul 23 '18 at 18:50
  • Your request will already be asynchronous, otherwise the `Response.Listener` would be pretty useless - Your asynctask will return before `Listener::onResponse` is called. – Mark Jul 23 '18 at 18:50
  • @GabeSechan Really? So Do I only need the code that is inside the doInbackground() method? – ProRiderZ115 Jul 23 '18 at 19:05
  • Possible duplicate of [Volley and AsyncTask](https://stackoverflow.com/questions/20675072/volley-and-asynctask) – J. Jefferson Jul 23 '18 at 21:16

0 Answers0