Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: variable has incorrect value in while loop

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:

  1. Create a new project in Android Studio, blank Activity
  2. Add the following code to the main activity

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.

like image 730
Hielko Avatar asked Nov 23 '15 20:11

Hielko


1 Answers

If you are really sure that the written code works correctly then from now on, you must start to check (ordered):

  • configuration --> is your project configuration totally ok with Java versions, jdks or the Java version is compatible with used Android libraries? Are your Java and Andorid libraries correctly configured?
  • environment --> is your debugging emulator a 3rd party library or is your debugging device is a valid device to debug your code? Is your coding OS is compatible with your ide, Java version or Android libraries?
  • JVM --> Did you try uninstalling and reinstalling with the correct source for Java jdk with the version you are using?

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.

like image 144
Bahadir Tasdemir Avatar answered Oct 23 '22 11:10

Bahadir Tasdemir