Problem:
Android
crashes, ifyou try to write a text in an ad Textview with .setText
Description:
With a timer,
the current time should be written to an Android Activity text box for display
every second
Timer
timerActualDayTime = new Timer();
timerActualDayTime.schedule(new TimerTask() {
@Override
public void run() {
String
sCurrentDateTime= new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
_textViewCurrentDayTime.setText(sCurrentDateTime);
}
}, 1000, 1000);
//textViewActualTime
|
At the yellow
spot crashes off Android
Solution:
Timer does not have a handle on the UI
If you want
to write from java code to output (UI), then you need higher rights than a
timer has.
Here you have
to take a handler.
Java
Handler() allow access to other places such as the off-input UI
Solution: Switch to Handler()
Ok Solution
works
Solution Code
TextView
_textViewCurrentDayTime;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//< init >
_textViewCurrentDayTime
= findViewById(R.id.textViewCurrentDayTime);
refreshCurrentDateTime();
//</ init >
}
//========< #region: Methods >========
private void refreshCurrentDateTime() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
String
sCurrentDateTime= new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
_textViewCurrentDayTime.setText(sCurrentDateTime);
//< loop: next
>
refreshCurrentDateTime();
//< loop: next
>
}
}, 1000);
}
//========</ #region: Methods >========
|