Yuval3210
Yuval3210

Reputation: 193

Changing TextView text from a thread

I know you can only change the text in tTxtViews from the UI thread but i cant seem to find a way to work with that.

I'll go in to a bit more details: I'm trying to have a TextView that displays the time passed, but I can't do it in a thread, or a method that keeps getting called. can you help me with a way of doing this? because I'm pretty much out of ideas.

Thanks.

Upvotes: 1

Views: 2609

Answers (2)

deadfish
deadfish

Reputation: 12304

        public class MainActivity extends Activity {

            protected static final long TIMER_DELAY = 100;
            private TextView tv;
            protected Handler handler;

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

                tv = (TextView)findViewById(R.id.helloWorld);
                handler = new Handler();
                handler.post(timerTask);


            }

            private Runnable timerTask = new Runnable() {
                public void run() {
                    Calendar now = Calendar.getInstance();

                    //format date time
                    tv.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND)));

                    //run again with delay
                    handler.postDelayed(timerTask, TIMER_DELAY);
                }
            };


        }

I forgot add this, sorry. Don't forget do this:

@Override
    public void onPause() {

        if (handler != null)
            handler.removeCallbacks(timerTask);

        super.onPause();
}

And if you want resume app try this

@Override
    public void onResume() {
        super.onResume();

        if (handler != null)
            handler.post(timerTask);
}

Upvotes: 2

Leandros
Leandros

Reputation: 16825

Use this

new Thread(new Runnable() {

    @Override
    public void run() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // Do what you want.
            }          
        });
   }         
}).start();

or use a Handler:

Runnable r = new Runnable() {

    @Override
    public void run() {
        // Do what you want.
    }
};
Handler mHandler = new Handler();
mHandler.post(r);

Upvotes: 2

Related Questions