【问题标题】:Query on Android Call log skips first record查询 Android 通话记录会跳过第一条记录
【发布时间】:2015-04-21 23:27:27
【问题描述】:

我正在尝试使用以下代码获取 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;

这对大多数呼叫都有效,除了顶部的呼叫(最新的,因为我按日期排序,降序)。

这怎么可能?

【问题讨论】:

    标签: android database cursor call calllog


    【解决方案1】:
    cursor.moveToFirst()
    

    将移动到第一行。到目前为止,一切都很好。但是你正在做

    while(cursor.moveToNext()) {
    }
    

    再次将光标移动到下一行,即第二行,从而跳过第一行。

    【讨论】:

      【解决方案2】:

      Melquiades 关于您的问题根源是正确的,但是您的解决方案有问题。 SQLiteDatabase.query 位于第一个元素之前,这就是您的 while 循环目前正在工作的原因,但是您没有检查查询返回的游标中是否包含任何元素。

      这是一个 sn-p,它既检查空游标又不跳过第一个元素。

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

      【讨论】:

        猜你喜欢
        • 2018-11-20
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        • 2023-03-27
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多