Reputation: 3
Hey i recently got into android and made my first app which was meant to start a run down timer of 60 seconds when the user pressed start button. The application sets the content view fine and displays 60 but when i click the start button it displays 59 successfully and then the app crashes.Here's the code(it has only one activity)
public class test1activity extends Activity
{
Thread countdown;
long f, pa, jee;
TextView ytvp;
String s;
TextView uyti;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ytvp = (TextView) findViewById(R.id.textView2);
uyti = (TextView) findViewById(R.id.tv2);
countdown = new Thread() {
public void run() {
jee = (System.currentTimeMillis()) / 1000;
while ((((System.currentTimeMillis()) / 1000) - jee) < 60)
{
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
f = ((System.currentTimeMillis()) / 1000) - jee;
pa = 60 - f;
s = String.valueOf(pa);
ytvp.setText(s);
}
}
}
};
}
public void whenclickstart(View view) {
countdown.start();
}
Upvotes: 0
Views: 81
Reputation: 24820
You cannot set UI elements from inside another thread(Non UI thread). So you cannot use this below line.
ytvp.setText(s);
Try something like this, you dont need threading for what you are trying to do
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
ytvp.setText("" + millisUntilFinished/1000);
}
public void onFinish() {
ytvp.setText(""+0);
}
}.start();
If you do not want to use countdowntimer replace setText with
runOnUiThread(new Runnable() {
public void run() {
ytvp.setText(s);
}
});
Upvotes: 2