mcm mcm - 5 months ago 15
Android Question

Problems with sleep() in combination with a network task on Android

I need to implement a download task which emits a string which I show in a textview. This works perfectly with this method.

Because of data protection the text in the view shall be deleted after ca. 10 seconds and thats where my problems start.

This is my onPostExecute()-method:

protected void onPostExecute(String result) {
txtOutput.setText(result);
int i = 0;
while (txtOutput.getText().toString().equals("") && i <= 30) {
TimeUnit.SECONDS.sleep(1);
i++;
}
TimeUnit.SECONDS.sleep(10);
txtOutput.setText("");
}


The while-loop is there, so the 10 seconds don't start until the output is shown.

My problem is that the output never is shown.

/edit: I adjusted the String comparison

Answer

To compare string you need to use the equals() method not ==. You can also use isEmpty() So try

protected void onPostExecute(String result) {
    txtOutput.setText(result);

    new Handler().postDelayed(new Runnable(){
        public void run() {
            txtOutput.setText("");
        }
    }, 10000);        
}

Also do not sleep the Ui Thread (more here)

Comments