0

I'm just learning Java and here I'm presented with this strange error message. In the code below:

while (phones_cursor.moveToNext())
{
  String name = phones_cursor.getString(phones_cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
Log.wtf("Name: ", name);

I'm get this message saying that "name" cannot be resolved to a variable. So I suppose name is local to the while loop. I wonder now however, how do I get this variable out of the while loop?

1
  • 3
    well...now you have 3 equal answers :D Commented Sep 27, 2013 at 12:01

3 Answers 3

6

define the variable outside of the loop

String name = null;

while (phones_cursor.moveToNext())
{
  name = phones_cursor.getString(phones_cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
Log.wtf("Name: ", name);

this is because every block (starting with { and ending with }) has it's own scope. but inner scope can access variables from outer scopes.

Sign up to request clarification or add additional context in comments.

1 Comment

But keep in mind, that the above code iterates over all phone_cursor entries, but will only keep and print the value of the last entry.
4

You have to define your variable outside the loop:

String name = null;

while (phones_cursor.moveToNext())
{
    name = phones_cursor.getString(phones_cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}

Log.wtf("Name: ", name);

Comments

3

Those variable is out of scope.

In java the scope is restricted to {}.

Just move that variable declaration to top, so that they available further.

    String  name = null;
    while (phones_cursor.moveToNext())
    {
      name = phones_cursor.getString(phones_cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    }
    Log.wtf("Name: ", name);

Prefer to read : Block and Statements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.