I want to count from 1 till 15 for example and go from 15 till it reaches 1 and repeats the process... may you please help me complete? I tried everything. Instead of if, I tried While, it gave random numbers for some reason. This method only subtracts to 14. It won't completely countdown.
int counter = 0;
int total = 15;
number = (TextView) this.findViewById(R.id.number);
final Timer c=new Timer();
c.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (counter < total && timerHasStarted ) {
runOnUiThread(new Runnable()
{
@Override
public void run()
{
number.setText("" +counter );
counter++;
}
});
}
if (counter <= total && timerHasStarted ) {
runOnUiThread(new Runnable()
{
@Override
public void run()
{
number.setText("" +counter );
counter++;
}
});
if (counter == total && timerHasStarted) {
countingDown = true;
if(countingDown){
counter--;
}
else{
counter++;
}
//setting the text here
if(counter%15==0){ //only 0 when counter equals 0 or 15
countingDown=!countingDown; // starting the other direction at next time
}
}
}}}, 1000, 300);
timerHasStarted = true;
You didnt provide the whole code but nevertheless
Your logic has a big flaw:first counter is 0 so the first if is gonna count it up because its under 15...it does so till it reaches the 15 then it does nothing...but here comes the second if now that counter is 15 it is executed making the counter back again to 14 so it alters between 14 and 15 the wohle time froom the point it reaches for the first time.
Heres my solution:
have a boolean like countingDown and set it to false at the beginning if it hits the 15 set it to true.
check this boolean what to do if countingDown is true/false.
like:
if(countingDown){
counter--;
}
else{
counter++;
}
//setting the text here
if(counter%15==0){ //only 0 when counter equals 0 or 15
countingDown=!countingDown; // starting the other direction at next time
}
Cheers