문제

Hi I would like to ask something about my code coz I can't find out why is that It adds more than 1 when I declare it to add 1 everytime the timer reaches 0?

here is my code

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer);

    timerView = (TextView)findViewById(R.id.timer);
    energyView = (TextView)findViewById(R.id.energy);

    counter = new MyCount (10000,10);
    counter.start();


}

public String formatTime(long millis) 
{
    output = "";
    seconds = millis / 1000;
    long minutes = seconds / 60;

    seconds = seconds % 60;
    minutes = minutes % 60;

    String secondsD = String.valueOf(seconds);
    String minutesD = String.valueOf(minutes);

    if (seconds < 10)
        secondsD = "0" + seconds;
    if (minutes < 10)
        minutesD = "0" + minutes;

    output = minutesD + ":" + secondsD;

    return output;
}
public class MyCount extends CountDownTimer 
{
    Context mContext;

    public MyCount(long millisInFuture, long countDownInterval) 
    {
        super(millisInFuture, countDownInterval);
    }


    public void onTick (long millisUntilFinished) 
    {
        timerView.setText ( formatTime(millisUntilFinished));

        if ( seconds == 0 )
        {

            Toast.makeText( getApplicationContext(), "Done", Toast.LENGTH_LONG ).show();
            energy = energy + 1;
            energyView.setText(Integer.toString(energy));
        }
    }

    public void onFinish() {}

}

My energyView is always showing random number but mostly 40+ everytime my seconds reaches 0 can anyone help me? thanks in advance

도움이 되었습니까?

해결책

The problem is that since you could enter the condition if ( seconds == 0 ) more than once. Suppose you enter the onTick with value 999 ms and then with 2ms. For both ms/1000 will give 0 (since it's an operation between longs). You should write that part taking that into consideration. As someone was suggesting in a comment you could simply get rid of the condition seconds==0 and increment your variable inside the onFinish

다른 팁

Where are you declaring your seconds variable and its type?

Also, even though you are initializing with only 10000 ms (10 s), I noticed that you have the following in formatTimer:

seconds = millis/1000;

followed by

seconds = seconds % 60;

and so you will get 0 every 60 seconds if you initialize with longer than 60 s!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top