Eyal
Eyal

Reputation: 1709

Android How to wait for an AsyncTask to finish

I have an AsyncTask which acts as a client and get a string from a server and puts it in a String. After the task I use the response from the server but the data haven't changed yet - it's null.

connectBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ...
        Client myClient = new Client(responseTV);
        myClient.execute();

        if (responseStr.charAt(0) == '1') {   <----- responseStr is null
            changeBrightness(Integer.parseInt(responseStr.substring(1)));
        }
    }
});

I assume the code keeps going after .execute() which is not very good in my situation.

Update: Added code for Client class.

public class Client extends AsyncTask<Void, Void, Void> {

    String response = "";
    TextView responseTV;

    public Client(TextView responseTV) {
        this.responseTV = responseTV;
    }

    @Override
    protected Void doInBackground(Void... params) {
        Socket socket = null;

        try {
            socket = new Socket(IP, PORT);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];

            int bytesRead;
            InputStream inputStream = socket.getInputStream();

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        //Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
        responseTV.setText(response);
        responseStr = response;
        super.onPostExecute(aVoid);
    }
}

Upvotes: 1

Views: 917

Answers (1)

Piyush
Piyush

Reputation: 1784

if (responseStr.charAt(0) == '1') {   <----- responseStr is null
            changeBrightness(Integer.parseInt(responseStr.substring(1)));
        }

Use this code in onPostExecute() method of AsyncTask. It runs on the UI thread and is exactly the method you need after finishing work in doInBackground().

Upvotes: 3

Related Questions