I’m building a simple clock on android.
My problem is on the while loop, when I use Thread.sleep(5000) I get error: “Unhandled exception type InterruptedException“.
How should I run the loop so it works correctly? There aren’t too many lines of code so I copied it entirely, hopefully will be useful for somebody since I haven’t been able to find many examples of clocks.
public class MainActivity extends Activity {
TextView hours;
TextView minutes;
Calendar c;
int cur_hours;
int cur_minutes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clock_home);
hours = (TextView) findViewById(R.id.hours);
minutes = (TextView) findViewById(R.id.minutes);
while (true) {
updateTime();
Thread.sleep(5 * 1000); // Unhandled exception type InterruptedException
}
}
public void updateTime() {
c = Calendar.getInstance();
hours.setText("" + c.get(Calendar.HOUR));
minutes.setText("" + c.get(Calendar.MINUTE));
}
}
Thread.sleep throws InterruptedException, you need to either catch (or) rethrow.
Wrap Thread.sleep call inside
try/catchExample:
EDIT:
As InterruptedException javadoc