Reputation: 55
EDIT: I have found the problem and it is the Thread.Sleep is there any other way of making my application wait a second?
I'm trying to learn android development so I'm using android studio. I have an activity, which isn't the main activity and I tried to build a timer that starts counting from 40 minutes when the activity starts, but for some reason when I press the button in the main activity that is supposed to change the activity to the one with the timer, the app crashes. This is the timer's activity code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Timer extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
}
@Override
protected void onStart() {
String counter;
int totalSeconds = 2400;
int minLeft, secLeft;
for (int i = totalSeconds; i > 0; i--)
{
try
{
Thread.sleep(1000L);
}
catch (InterruptedException e) {e.printStackTrace();}
minLeft=(int)Math.floor(i/60);
secLeft=i-(minLeft*60);
counter = minLeft+":"+secLeft;
TextView tv = (TextView)findViewById(R.id.timer);
tv.setText(counter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Upvotes: 0
Views: 257
Reputation: 4840
You need to move all of your counter logic off of your main thread. Try something like this:
private int secondsLeft = 2400;
private Handler mHandler = new Handler();
public void onStart() {
super.onStart();
final TextView tv = (TextView)findViewById(R.id.timer);
mHandler.postDelayed(new Runnable() {
public void run() {
secondsLeft--;
int minLeft = (int)Math.floor(secondsLeft / 60);
int secLeft = secondsLeft - (minLeft * 60);
tv.setText(minLeft + ":" + secLeft);
if (secondsLeft > 0)
mHandler.postDelayed(this, 1000);
}
}, 1000);
Upvotes: 1
Reputation: 2224
You probably missed to call super.onStart()
in your overridden onStart()
Upvotes: 0