-2

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);
itaied
  • 6,827
  • 13
  • 51
  • 86

2 Answers2

2

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);
JiTHiN
  • 6,548
  • 5
  • 43
  • 69
  • for some reason it says that activityContext doesn't have the method runOnUiThread – itaied May 10 '14 at 13:26
  • Forgot to mention that. You have to cast it to `Activity`. See the updated answer. – JiTHiN May 10 '14 at 14:24
  • I didn' try it but thanks anyway, I used the handler solution. Do you know any advantages\disadvantages of one over the other? – itaied May 10 '14 at 14:34
  • Refer this SO question: http://stackoverflow.com/questions/12618038/why-to-use-handlers-while-runonuithread-does-the-same Using `runOnUiThread` ensures that your code will run in the UI thread. – JiTHiN May 10 '14 at 15:02
1

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);
}