Hello i wanna do apliacation which every 1 second call function or do something else. I have this code which is not working can you tell what is wrong?
public class App5_Thread extends Activity implements Runnable {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
TextView tv1 = (TextView) findViewById(R.id.tv);
showTime(tv1);
try {
Thread.sleep(1000);
}catch (Exception e) {
tv1.setText(e.toString());
}
}
public void showTime(TextView tv1 ){
String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
tv1.setText(sdf.format(cal.getTime())+" "+System.currentTimeMillis());
}
}
You don't have a loop in run() function, try to change it like this:
@Override
public void run() {
TextView tv1 = (TextView) findViewById(R.id.tv);
while(true){
showTime(tv1);
try {
Thread.sleep(1000);
}catch (Exception e) {
tv1.setText(e.toString());
}
}
}
Be careful, it will run forever though. You should also use a handler to perform changes on UI from another thread, it can be done by example below:
Handler mHandler = new Handler();
@Override
public void run() {
final TextView tv1 = (TextView) findViewById(R.id.tv);
while(true){
try {
mHandler.post(new Runnable(){
@Override
public void run() {
showTime(tv1);
}
);
Thread.sleep(1000);
}catch (Exception e) {
//tv1.setText(e.toString());
}
}
}
Like I said before, you got to modify your textView in the UI thread (the thread that created the component).
In order to do that use a Handler, like this : (Do not loop in your thread, just post a message to the handler)
private TextView tv1;
Handler tick_Handler = new Handler();
MyThread tick_thread = new MyThread();
private class MyThread implements Runnable {
public void run() {
String txt = "Vlakno id:" + Thread.currentThread().getId()+" THREAD";
Log.v("MyActivity", txt);
//tv1.setText(txt);
showTime(tv1);
tick_Handler.postDelayed(tick_thread, 1000);
}
}
String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
private void showTime(TextView tv ){
Calendar cal = Calendar.getInstance();
tv.setText(sdf.format(cal.getTime())+" "+System.currentTimeMillis());
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.tv);
tick_Handler.post(tick_thread);
}
By the way, if you want to have an accurate timer, you should tick every 300 ms. You might see some strange seconds if you perform your "showtime" method every second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With