2015-04-21 108 views
0

我想使用此代碼來獲取在android通話記錄所有來電:查詢Android上的通話記錄跳過第一個記錄

ArrayList<Call> list = new ArrayList<Call>(); 
    Cursor cursor; 
    // The fields we want to select from the internal database. Setting this 
    // to null is equivalent to * (e.g., SELECT * FROM...) 
    String[] projection = {CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.TYPE}; 
    String sortOrder = CallLog.Calls.DATE + " desc"; 
    int numberCol = 0; 
    String contactName; 
    String contactNumber; 
    String contactDate; 
    int callType; 
    Call phone_call; 

    // Query the CallLog table, selecting only the number and date then sorting it by the date. 
    cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, sortOrder); 

    numberCol = cursor.getColumnIndex(CallLog.Calls.NUMBER); 

    if(cursor.moveToFirst()) { 

     while(cursor.moveToNext()) { 
      //do stuff 
     } 
    } 

    cursor.close(); 

    return list; 

這工作,對於大多數呼叫,除了最上面的一個(最新,因爲我按日期排序,降序)。

這怎麼可能?

回答

3
cursor.moveToFirst() 

將移動到第一行。到現在爲止還挺好。但那麼你在做

while(cursor.moveToNext()) { 
} 

它再次移動光標,這次是下一行,這是第二個,因此跳過第一行。

+0

謝謝!刪除第一行,現在它的作品 – user3287740

1

Melquiades對您的問題的來源是正確的,但是您的解決方案有問題。 SQLiteDatabase.query被定位在第一個元素之前,這就是爲什麼你的while循環正在工作,但是你並沒有檢查查詢返回的遊標是否有任何元素。

這是一個代碼片段,它既檢查空遊標,又不跳過第一個元素。

if (cursor.moveToFirst()) { 
    do { 
     // Handle each element of the query 
    } while (cursor.moveToNext()) 

} else { 
    // cursor contains no results 
} 
+0

點@Derek :) – Melquiades