Update TextView Every Second

AndroidDateTimeTextviewClock

Android Problem Overview


I've looked around and nothing seems to be working from what I've tried so far...

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

	TextView tvTime = (TextView) findViewById(R.id.tvTime);
	TextView tvDate = (TextView) findViewById(R.id.tvDate);

	java.util.Date noteTS = Calendar.getInstance().getTime();

	String time = "hh:mm"; // 12:00
	tvTime.setText(DateFormat.format(time, noteTS));

	String date = "dd MMMMM yyyy"; // 01 January 2013
	tvDate.setText(DateFormat.format(date, noteTS));

I basically want the setText methods to update or refresh every second or so, so my clock actually works like it should do. I've seen methods like handlers and run and nothing worked so any help with this would be great thanks. :)

Android Solutions


Solution 1 - Android

Add following code in your onCreate() method:

Thread thread = new Thread() {

  @Override
  public void run() {
    try {
      while (!thread.isInterrupted()) {
        Thread.sleep(1000);
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            // update TextView here!
          }
        });
      }
    } catch (InterruptedException e) {
    }
  }
};

thread.start();

This code starts an thread which sleeps 1000 milliseconds every round.

Solution 2 - Android

It's a very old question and I'm sure there are a lot of resources out there. But it's never too much to spread the word to be at the safe side. Currently, if someone else ever want to achieve what the OP asked, you can use: android.widget.TextClock.

TextClock documentation here.

Here's what I've used:

<android.widget.TextClock
    android:id="@+id/digitalClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timeZone="GMT+0000" <!--Greenwich -->
    android:format24Hour="dd MMM yyyy   k:mm:ss"
    android:format12Hour="@null"
    android:textStyle="bold"
    android:layout_alignParentEnd="true" />

Solution 3 - Android

If you want to show time on textview then better use Chronometer or TextClock

Using Chronometer:This was added in API 1. It has lot of option to customize it.

Your xml

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp" />

Your activity

Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();

Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.

Your xml

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="44sp"
    android:textStyle="bold" />

Thats it, you are done.

You can use any of these two widgets. This will make your life easy.

Solution 4 - Android

Extending @endian 's answer, you could use a thread and call a method to update the TextView. Below is some code I made up on the spot.

java.util.Date noteTS;
String time, date;
TextView tvTime, tvDate;

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

	tvTime = (TextView) findViewById(R.id.tvTime);
	tvDate = (TextView) findViewById(R.id.tvDate);

	Thread t = new Thread() {

		@Override
		public void run() {
			try {
				while (!isInterrupted()) {
					Thread.sleep(1000);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							updateTextView();
						}
					});
				}
			} catch (InterruptedException e) {
			}
		}
	};

	t.start();
}

private void updateTextView() {
	noteTS = Calendar.getInstance().getTime();

	String time = "hh:mm"; // 12:00
	tvTime.setText(DateFormat.format(time, noteTS));

	String date = "dd MMMMM yyyy"; // 01 January 2013
	tvDate.setText(DateFormat.format(date, noteTS));
}

Solution 5 - Android

You can use Timer instead of Thread. This is whole my code

package dk.tellwork.tellworklite.tabs;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import dk.tellwork.tellworklite.MainActivity;
import dk.tellwork.tellworklite.R;

@SuppressLint("HandlerLeak")
public class HomeActivity extends Activity {
	Button chooseYourAcitivity, startBtn, stopBtn;
	TextView labelTimer;
	int passedSenconds;
	Boolean isActivityRunning = false;
	Timer timer;
	TimerTask timerTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_home);
		
		chooseYourAcitivity = (Button) findViewById(R.id.btnChooseYourActivity);
		chooseYourAcitivity.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//move to Activities tab
				switchTabInActivity(1);
			}
		});
		
		labelTimer = (TextView)findViewById(R.id.labelTime);
		passedSenconds = 0;
		
		startBtn = (Button)findViewById(R.id.startBtn);
		startBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isActivityRunning) {
					//pause running activity
					timer.cancel();
					startBtn.setText(getString(R.string.homeStartBtn));
					isActivityRunning = false;
				} else {
					reScheduleTimer();
					startBtn.setText(getString(R.string.homePauseBtn));
					isActivityRunning = true;
				}
			}
		});
		
		stopBtn = (Button)findViewById(R.id.stopBtn);
		stopBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				timer.cancel();
				passedSenconds = 0;
				labelTimer.setText("00 : 00 : 00");
				startBtn.setText(getString(R.string.homeStartBtn));
				isActivityRunning = false;
			}
		});
	}
	
	public void reScheduleTimer(){
		timer = new Timer();
		timerTask = new myTimerTask();
		timer.schedule(timerTask, 0, 1000);
	}
	
	private class myTimerTask extends TimerTask{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			passedSenconds++;
			updateLabel.sendEmptyMessage(0);
		}
	}
	
	private Handler updateLabel = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			//super.handleMessage(msg);
			
			int seconds = passedSenconds % 60;
			int minutes = (passedSenconds / 60) % 60;
			int hours = (passedSenconds / 3600);
			labelTimer.setText(String.format("%02d : %02d : %02d", hours, minutes, seconds));
		}
	};
	
	public void switchTabInActivity(int indexTabToSwitchTo){
		MainActivity parentActivity;
		parentActivity = (MainActivity) this.getParent();
		parentActivity.switchTab(indexTabToSwitchTo);
	}
}

Solution 6 - Android

This Code work for me..

//Get Time and Date
private String getTimeMethod(String formate)
{
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat(formate);
    String formattedDate= dateFormat.format(date);
    return formattedDate;
}

//this method is used to refresh Time every Second
private void refreshTime() //Call this method to refresh time
{
    new Timer().schedule(new TimerTask() {
    	@Override
    	public void run() {
    	    runOnUiThread(new Runnable() {
    	    	@Override
    	    	public void run() {
    	    	    txtV_Time.setText(getTimeMethod("hh:mm:ss a")); //hours,Min and Second with am/pm
    	    	    txtV_Date.setText(getTimeMethod("dd-MMM-yy")); //You have to pass your DateFormate in getTimeMethod()          
    	    	};
        	});
        }
    }, 0, 1000);//1000 is a Refreshing Time (1second)
}

Solution 7 - Android

java 8 lamdas:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(() -> {
            //code here...
            String str = getDeltaTimeHumanString(instant,Instant.now()) 
            myTextView.setText(str);
        });
    }
}, 1000, 1000);

easy

Solution 8 - Android

Use TextSwitcher (for nice text transition animation) and timer instead.

Solution 9 - Android

You can also use TimerTask for that.

Here is an method

private void setTimerTask() {
    long delay = 3000;
    long periodToRepeat = 60 * 1000; /* 1 mint */
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //   do your stuff here.
                }
            });
        }
    }, 3000, 3000);
}

Solution 10 - Android

It would be better if you just used an AsyncTask running using a Timer something like this

 Timer LAIATT = new Timer();
    TimerTask LAIATTT = new TimerTask()
    {
        @Override
        public void run()
        {
            LoadAccountInformationAsyncTask LAIAT = new LoadAccountInformationAsyncTask();
            LAIAT.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    };
    LAIATT.schedule(LAIATTT, 0, 1000);

Solution 11 - Android

I you use Kotlin this way can help you:

val thread: Thread = object : Thread() {
            override fun run() {
                try {
                    while (!this.isInterrupted) {
                        sleep(1000)
                        runOnUiThread {
                            // update TextView And Random number here!
                            val rnds = (0..7).random()
                            tvBanner.text = textBanner[rnds]
                            
                        }
                    }
                } catch (e: InterruptedException) {
                }
            }
        }


thread.start()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimmoView Question on Stackoverflow
Solution 1 - AndroidendianView Answer on Stackoverflow
Solution 2 - AndroidAuroMetalView Answer on Stackoverflow
Solution 3 - AndroidShakeeb AyazView Answer on Stackoverflow
Solution 4 - AndroidAdamView Answer on Stackoverflow
Solution 5 - AndroidNamPhamView Answer on Stackoverflow
Solution 6 - AndroidFra RedView Answer on Stackoverflow
Solution 7 - AndroidBarrretttView Answer on Stackoverflow
Solution 8 - AndroidK. OulebsirView Answer on Stackoverflow
Solution 9 - AndroidKhemraj SharmaView Answer on Stackoverflow
Solution 10 - AndroidAlpha Gabriel V. TimbolView Answer on Stackoverflow
Solution 11 - AndroidMoriView Answer on Stackoverflow