I'm trying to create an Android application that shows the current time. I want to update time on my Activity with the Timer, but the TextView is not updating, so just one time is always on the screen. Here is my code:
package com.example.androidtemp;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.example.androidtemp.R;
public class ActivityTime extends Activity
{
SimpleDateFormat sdf;
String time;
TextView tvTime;
String TAG = "States";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_time);
sdf = new SimpleDateFormat("HH:mm:ss");
time = sdf.format(new Date(System.currentTimeMillis()));
tvTime = (TextView) findViewById(R.id.tvTime);
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
@Override
public void run()
{
// TODO Auto-generated method stub
timerMethod();
}
};
try
{
timer.schedule(task, 0, 1000);
}
catch (IllegalStateException e)
{
// TODO: handle exception
e.printStackTrace();
Log.e(TAG, "The Timer has been canceled, or if the task has been scheduled or canceled.");
}
}
protected void timerMethod()
{
// TODO Auto-generated method stub
this.runOnUiThread(changeTime);
}
private final Runnable changeTime = new Runnable()
{
public void run()
{
// TODO Auto-generated method stub
//Log.d(TAG, "Changing time.");
sdf.format(new Date(System.currentTimeMillis()));
tvTime.setText(time);
}
};
}
Does anyone have solution for this problem?