Strange behavior in the Android "if" block

It goes like an error, it twitter like an error .... I need someone to confirm that it is an error.

I tried to get phone numbers from the address book using this code:

public JSONObject getAllPhones() throws JSONException{ 
String mPhoneNumberProjection[] = new String[] {
        Contacts.Phones.NAME, Contacts.Phones.NUMBER, Contacts.Phones.TYPE
};
Uri phoneNumbersUri = Contacts.Phones.CONTENT_URI;
JSONObject result = new JSONObject(); 
JSONArray phones = new JSONArray();

Cursor myCursor = mApp.managedQuery(phoneNumbersUri, mPhoneNumberProjection, null, null, null);
mApp.startManagingCursor(myCursor);
if (!myCursor.isAfterLast()){
    myCursor.moveToFirst();
    do{
        JSONObject aRow = new JSONObject();
        for (int i = 0; i < myCursor.getColumnCount(); i++){
            Log.d(LOG_TAG, myCursor.getColumnName(i) + " -> " + myCursor.getString(i));
            aRow.put(myCursor.getColumnName(i), myCursor.getString(i));
        }
        phones.put(aRow);
    } while (myCursor.moveToNext());
}
result.put("phones", phones);
result.put("phoneTypes", getPhoneTypes());
return result;
}

But when there are no contacts, and! myCursor.isAfterLast () evaluates to false, the program goes into the for loop. Thus, it enters the if block, skips several methods, and lands in the for loop ...

When I extract this loop into a separate function, everything works fine.

I do this in Eclipse Helios on 32-bit Vista. I tried to clear the project, erase the Java cache, restart the computer, create a new AVD ... I used Android 1.6 and Android 2.2, but the error remains ...

Can someone explain what is happening?

+3
5

, , , , :)

+1

, . , . ? ( ), , .


- ( JD Java Decompiler, , Android) , , id - , . → → Android.

0

, isAfterLast false, 0 ?;) moveToFirst()? false, , isAfterLast() .

0

, if while

try {
    if (c!=null) {
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
               //stuff here
        }
    }
} finally {
    if (c!=null) {
        c.close();
    }
}
0

I believe that theAfterLast works as intended. isAfterLast will be false because there are no lines as you stated, so it can never evaluate whether it is on the last line.

Plus, in the above code example, which you never moved to the first line before calling isAfterLast (), the if statement will never be evaluated again.

using

if (cursor.moveToFirst()) {
       // code
    while(cursor.isAfterLast() == false) {
        // code
     String[] columNames = cursor.getColumnNames();
     for (String column : columnNames)  {
         aRow.put(column, cursor.getString(cursor.getColumnIndex(column))); 
     }
    cursor.moveToNext();
    phones.put(aRow);

    }
}

Hope this helps.

0
source

Source: https://habr.com/ru/post/1755668/


All Articles