Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find local variable 'ac'

Below my code but it is not working - refer to this screenshot of the error during debugging,

Cannot find local variable 'ac'

    AccountManager am = AccountManager.get(this);
    Account[] accounts = am.getAccounts();
    for (final Account ac : accounts)
    {
        String acname = ac.name;
        System.out.println("Accounts : " + acname);

    }
like image 821
S.BM Avatar asked Oct 19 '16 05:10

S.BM


1 Answers

From your screenshot I saw that you are using Android Studio and there is no problem with your code, but rather some debug settings. If you'll open Android Studio preferences and go to Build, Execution, Deployment > Debugger > Data Views you'll probably see the option Enable auto expressions in Variables view ticked, since it is ticked by default. It should look something like this: Android Studio Preferences Now, if you'll check the IntelliJ docs for that you'll find this (note that IntelliJ and Android Studio are running on the same engine in case that you are wondering why I said about IntelliJ docs):

Select this option if you want the IntelliJ IDEA debugger to automatically evaluate expressions and show the corresponding values in the Variables pane of the Debug tool window.

The debugger analyzes the context near the breakpoint (the current statement, one statement before, and one after). It does so to find various expressions in the source code (if available) such as, for example, myvar.myfield.

If such expressions don't contain explicit method invocations, the debugger evaluates them and shows the corresponding values in the Variables view.

Basically, they are saying that the IDE will check the code around a breakpoint to identify the variables and compute their values (method calls not included). That being said, when the control reaches the line where accounts variable is declared, the IDE will check the code for variables and will found the ac variable, but will fail to compute its values since at the execution point that variable isn't declared yet, hence the entire operation will end with the message that the variable cannot be found.
To fix this, you have to uncheck that option from settings or you can leave it just like this, since it will not affect your code (it is fully functional right now).

like image 187
Iulian Popescu Avatar answered Oct 25 '22 13:10

Iulian Popescu