Question

I have a text view in my android activity, and I want to pass it to a function in another java class and modify its text. But it throws me an exception. I read that I need to run it on a UI thread or send to context variable, but I'm a bit confused and I couldn't manage to do it. That's my code:

Java timer class

public class CountdownTimer {
static int duration;
static Timer timer;

public static void startTimer(final TextView TVtime) {
    duration = 10;

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            TVtime.setText(setDuration());
        }
    }, 1000, 1000);
}

private static String setDuration(){
    if(duration == 1)
        timer.cancel();
    return String.valueOf(--duration);
}
}

Android activity:

TVtime = (TextView) findViewById(R.id.textView_displayTime);
CountdownTimer.startTimer(TVtime);
Was it helpful?

Solution 2

You can use android.os.Handler for that :

public static void startTimer(final TextView TVtime) {
    duration = 10;

    final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            TVtime.setText((String) msg.obj);
        }
    };

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            Message msg = new Message();
            msg.obj = setDuration();
            handler.sendMessage(msg);
        }
    }, 1000, 1000);
}

OTHER TIPS

You cannot update the UI from a non-UI Thread. Pass the activity Context to the startTimer() method.

public static void startTimer(final TextView TVtime,final Context activityContext) {
    duration = 10;

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

       public void run() {
          ((Activity) activityContext).runOnUiThread(new Runnable() {
                public void run()
                {
                     TVtime.setText(setDuration());
                }
            });
..........................
.......................

Android activity:

TVtime = (TextView) findViewById(R.id.textView_displayTime);
CountdownTimer.startTimer(TVtime, YourActivity.this);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top