1

我的问题似乎很愚蠢,但下面的代码让我很头疼。下面的代码打印contactIdtelephone number显示。

它运作良好,但我需要更清楚地知道一些事情:

 ContentResolver solver = getContentResolver();
            String mess="";

            Cursor cursor = solver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
            while (cursor.moveToNext()){
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                mess = mess + "ID: "+contactId+"\n";

                Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
                while (phones.moveToNext()) { 
                     String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));    
                     mess = mess + phoneNumber + "\n";
                  } 
            }

我不知道的是上面这行代码:

Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);

关于Android Development第三个参数:

selection :声明要返回哪些行的过滤器,格式化为 SQL WHERE 子句(不包括 WHERE 本身)。传递 null 将返回给定 URI 的所有行。

因此,作为这个定义,CONTACT_ID充当“A ROW”。(因为它filter which row to return),

但作为这一行,CONTACT_ID充当“A COLUMN”:

String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

请为我解释这一点。

谢谢 :)

4

3 回答 3

1

它是一个列(声明如下INTEGER PRIMARY KEY AUTOINCREMENT)。在:

Cursor phones = getContentResolver().query( 
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                    null, 
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, 
                    null, null);

您查询ContentProvider但使用_ID列来过滤结果。你是说:“我想要列中的行,ContentProvider_ID只找到值contactId ”。在:

String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

_ID用于获取列索引整数(从该列获取值),因此您不必使用简单的数字,如 0、1、2 并可能避免错误。

编辑: 第二个参数(也称为投影)表示您要从提供者检索的数据列(null= 获取所有列)。您可以将第二个参数视为过滤器,您只会获得您在数组中指定的那些列(例如,您可能不想要几列,因为您不会使用它们,因此对于第二个参数,您设置一个字符串数组与您确实想要的列并省略您不需要的列)。第三个参数过滤行,第二个参数过滤你检索到的列()

于 2012-03-10T16:51:08.720 回答
1

你应该看一下sql查询,如果我们想从表A中选择列column1,如果它的值为5,那么我们将这个查询写成:

SELECT column1 From A WHERE column1=5

这意味着从表中选择 column1 值等于 5 的值。所以这里没有什么不寻常的。

于 2012-03-10T16:59:08.863 回答
0

CONTACT_ID 是一列。例如,当您使用“CONTACT_ID = 10”过滤器表达式时,您将获得其 CONTACT_ID 单元格中值为 10 的所有行。请参阅以下有关 SQL 中 where 子句的链接:http: //www.w3schools.com/sql/sql_where.asp

于 2012-03-10T16:45:51.610 回答