I have been trying to create a program that will output a working digital clock that will allow me to quickly access the date and time. I have the code to parse the time, however, I'm having difficulty updating the textview. I have this:
`public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = (TextView)findViewById(R.id.timer);
time = new Time();
time.setToNow();
timeString = time.toString();
changeTime = Parser(timeString);
time.setToNow();
timeString = time.toString();
changeTime = Parser(timeString);
timer.setText(changeTime);
}
private String Parser(String time){
String year = time.substring(0, 4);
String month = time.substring(4,6);
String day = time.substring(6, 8);
String hour = time.substring(9,11);
String minute = time.substring(11, 13);
String second = time.substring(13, 15);
String finalTime = hour + ":" + minute + ":" + second + " " + day + " " + month + " " + year;
//String finalTime = second;
return finalTime;
}`
How do I put this in a loop to constantly update the textview.
Thanks for any help you can give me.
Declare a Handler to update the TextView on the UI thread.
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
time = new Time();
time.setToNow();
timeString = time.toString();
changeTime = Parser(timeString);
timer.setText(changeTime);
}
};
Start a TimeTask that will update your TextView
int initialDelay = 1000; //first update in miliseconds
int period = 5000; //nexts updates in miliseconds
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
Message msg = new Message();
mHandler.sendMessage(msg);
}
};
timer.scheduleAtFixedRate(task, initialDelay, period);