my question seems silly but it makes me headache by below code. Below code print contactId and telephone number to Screen.
It works well, but something I need to know more clearer:
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";
}
}
The thing I don’t know is this line of above code:
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
As in Android Development about third parameter:
selection : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null will
return all rows for the given URI.
So, as this defination, CONTACT_ID acts as “A ROW”. (because it filter which row to return),
but as this line, CONTACT_ID acts as “A COLUMN”:
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Please explain for me this point.
thanks 🙂
It’s a column (declared like this
INTEGER PRIMARY KEY AUTOINCREMENT). In:you query the
ContentProviderbut use the_IDcolumn to filter the results. You are saying: “I want the rows from theContentProviderwhere in the column_IDI find only the value contactId“. In:_IDis used to get the column index integer(to get the values from that column) so you don’t have to use simple numbers like 0, 1, 2 and possible avoid mistakes.Edit:
The second parameter(also referred as projection) represents the columns of data that you want to retrieve from the provider(
null= get all columns). You could look at the second parameter as a filter, you only get those column that you specified in the array(for example maybe you don’t want several columns because you will not use them, so for the second parameter you set a string array with the columns that you do want and omit the ones that you don’t need). The third parameter filter the rows, the second parameter filter the columns you retrieved()