I am facing a very silly problem in my project and not able to resolve it. I am using AsyncTask for fetching current location of user. In that i used one counter to work as timer. Inside doInBackground I am incrementing that counter and if its greater than x value then i cancel the async task.
Here is the code snippet : –
class CurrentPositionTask extends AsyncTask<String, Void, Void> {
long counter = 0;
boolean flag = true;
@Override
public void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
public Void doInBackground(String... params) {
// TODO Auto-generated method stub
do {
counter++;
if (latitude != 0 && longitude != 0) {
flag = false;
}
} while (counter <= 100000);
return null;
}
@Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
But here the while condition is not working. I also tried the for loop instead of while but that is not also working for me. Also face very strange problem, when i print the counter using sysout its working fine but without it its not working..
All suggestions are welcome.
This loop
will go on as long as any of the conditions hold, so it will continue while counter <= 10000 or flag is true. If
flagisfalsebutcounteris less than100000it will continue. If you intend to terminate the loop whenflagisfalse, then you need to do instead:Update: It seems from your comments that you expect the hundred thousand incrementation of the
countervariable to take roughly 20-30 seconds. Current day processors are way faster than that. I won’t even mention the speed variation between processors, because its negligible anyway. You can wait for real 30 seconds with this loop, though is a busy-waiting loop (just like your original intent) and not something nice to do: