When developing an Android app in Android Studio, a variable used within a while loop has an incorrect value. I reduced it in a test case to a very simple case:
method onStart:
@Override
public void onStart() {
super.onStart();
int count = 2;
int index = 1;
int value = 23;
Log.i("test", "value before = " + value);
while (index < count) {
Log.i("test", "value in while loop = " + value);
index++;
value = 0;
}
}
The output when executing the test app is:
value before = 23
value in while loop = 0
while the result should be
value in while loop = 23
When debugging, the result is as expected ('value in while loop = 23'), but in a regular debug build, it is wrong. The disassembled code of the main activity class looks ok, the value of the variable 'value' is set to 0 at the end of the while loop body. When some code or a function within the while loop body uses the variable 'value' it will have the value 0 instead of 23. In the test case I use the Log statement to simplify.
It doesn't go wrong when I change the line
value = 0;
to
if (value == 23) {
value = 0;
}
or when I remove the line
value = 0;
So it looks like some optimization error. But what optimization is done that could cause this? It makes the code unreliable.
If you are really sure that the written code works correctly then from now on, you must start to check (ordered):
Maybe you must give some details about your environment like Java version, Android min version, OS or the IDE you are using.
I hope those bullets will make you some correct associations to resolve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With