Вопрос

I'm writing an app for android in Java, and the server side also with Java. The connection is through sockets. To send strings to the server I'm using asyncTask as follows:

public static void send(String content) throws IOException {
    mConnectionHandler.new AsyncSendToServer().execute(content);
}

private class AsyncSendToServer extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... params) {
        out.println(params[0]);
        return null;
    }
}

Now the response from the server is done as follows:

public static String receive() {
    mConnectionHandler.new AsyncReceiveFromServer().execute();
    return serverResponse;
}

private class AsyncReceiveFromServer extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String result = null;
        try {
            result = in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    protected void onPostExecute(String result) {
        serverResponse = result;
    }
}

Because the methods are async, the serverResponse does not get the appropriate value in receive(). When I execute AsyncReceiveFromServer, receive() return the value of serverResponse before it's get updated in the asyncTask. What can I do in order to send the updated serverResponse?

Это было полезно?

Решение

Execute your AsyncReceiveFromServer from the onPostExecute of your AsyncSendToServer. This way, you are absolutely certain that the Send has finished.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top