内容解析器在什么情况下返回null游标?

时间:2017-11-20 10:08:08

标签: android android-contentresolver

我使用此代码的时间很长,而且只有少数时间我从内容解析器中获取null。我每次都在同一台设备上运行它,但不是每次我遇到这种情况。在什么情况下内容解析器返回null游标。

static HashMap<String, String> getCallDetails(final String phoneNo,final Context context) {
        HashMap<String, String> dataMap = new HashMap<>();
        Uri callUri = Uri.parse("content://call_log/calls");
        final Cursor cursor = context.getContentResolver().query(callUri, null, null, null, CallLog.Calls.DATE + " DESC");
        int duration;
        String dateTime;
        String dTime;
        int typeFlag;
        String callType = "";
        try {
            if (cursor != null) {
                String newNumber;
                while (cursor.moveToNext()) {
                    // newNumber is the most recent dialed or call received number
                    newNumber = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                    if (newNumber.contains(phoneNo)) {
                        duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
                        dTime = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
                        typeFlag = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                        switch (typeFlag) {
                            case CallLog.Calls.OUTGOING_TYPE:
                                callType = "OUTGOING";
                                break;
                        case CallLog.Calls.INCOMING_TYPE:
                            callType = "INCOMING";
                            break;
                    }
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    dateTime = formatter.format(new Date(Long.parseLong(dTime)));
                    dataMap.put("duration", String.valueOf(duration));
                    dataMap.put("dateTime", dateTime);
                    dataMap.put("callType", callType);
                    break;
                }
            }
        } else {
            appendLog("getCallDetails : cursor : cursor value is null");
        }
    } catch (Exception e) {
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        String className = Thread.currentThread().getStackTrace()[2].getClassName();
        appendLog("Exception in " + className + " : " + methodName + " : " + e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return dataMap;
}

1 个答案:

答案 0 :(得分:0)

试试这个

Cursor cursor = context.getContentResolver().query(
            CallLog.Calls.CONTENT_URI, null, null, null,
            CallLog.Calls.DATE + " DESC");
    int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = cursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);

可能对您有用