Vishal
Vishal

Reputation: 999

Android thread not working

In this code snippet, the application sleeps for the interval, but instead of appending TEXT to textStatus(TextView variable), it displays an error that Something went wrong and application is closing.

     Thread time_manager = new Thread(){
        public void run(){
            int interval = 2000;
            try{
                    sleep(interval);
                    textStatus.append("\nTEXT\n");

            } 
            catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
            }
        }
    };

What part am I doing wrongly?

Upvotes: 0

Views: 1473

Answers (2)

Lalit Poptani
Lalit Poptani

Reputation: 67296

To update the UI you can also use Handler like this, it will update your UI incrementing the value of counter everytime by 1 within every second.

int response = 0;
public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (TextView)findViewById(R.id.myid);
        thread t = new thread();
        t.start();
    }

public class thread extends Thread {
    public void run() {
        while (response < 100) {
            handler.sendEmptyMessage(0);
            response++;
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {

            tv.setText("helloworld " + response);
        }
    };

Upvotes: 1

Yashwanth Kumar
Yashwanth Kumar

Reputation: 29131

all the changes to the UI Part should be done on the UIThread, you should use something like post, or runOnUithread functions to update UI.

Upvotes: 1

Related Questions