2015-04-21 109 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