Include only person-based contacts when querying ContactsContract.Contacts - android

I have a SearchView in which if I type a name, it shows a autocomplete list of names matching it. However contacts like Facebook ambulance and AL Cricket also come in these results. How to exclude such results and only get those contacts that are of actual people?
Code I am using to get display name is this :
private String getDisplayNameForContact(Intent intent) {
Cursor phoneCursor = getContentResolver().query(intent.getData(), null, null, null, null);
phoneCursor.moveToFirst();
int idDisplayName = phoneCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String name = phoneCursor.getString(idDisplayName);
phoneCursor.close();
return name;
}

You need to add a selection and selection arguments to your contentResolver.query.
The arguments you want are:
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?";
String[] selectionArgs = {"1"};
You add them like so:
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor contactsCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, selection, selectionArgs, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
The constant ContactsContract.Contacts.IN_VISIBLE_GROUP determines what subgroup of contacts you are querying.

As you can see, when you call - query(intent.getData(), null, null, null, null) - get all list data. Where is null, theare is your selections parameters. It remains only to choose the appropriate options. Try my example, and swith different values (ContactsContract.CommonDataKinds.SomethingElse).
I hope this helps.
private static Cursor allContactsQuery(Context context) {
final String[] CONTACTS = new String[]{
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.Contacts.LOOKUP_KEY,
};
String SELECTION = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY +
"<>''" + " AND " + ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1" +
" AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1";
final String[] SELECTION_ARGS = null;
final String SORT_ORDER = ContactsContract.Contacts.SORT_KEY_PRIMARY;
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
CONTACTS,
SELECTION,
SELECTION_ARGS,
SORT_ORDER);
return cursor;
}

Related

Unable to get songs according to album and artists

I want to show songs according to artists and albums but i am unable to query for it.
String[] projection = new String[] { MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.NUMBER_OF_SONGS };
String selection = null;
String[] selectionArgs = null;
String sortOrder = MediaStore.Audio.Media.ALBUM + " ASC";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, projection, null, null, null);
Can anyone tell me what's wrong with this code ?
If you are putting null in your resolver.query, you do not need to assign variables selection and SelectionArgs.
On the face of it I can not see anything wrong but you have not listed any errors or what the outcome actually is.
However this is how I do it:
public Cursor getAlbums(Context context) {
String[] dataColumns;
ContentResolver resolver = context.getContentResolver();
dataColumns = new String[]{
BaseColumns._ID,
MediaStore.Audio.AlbumColumns.ALBUM,
MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,
MediaStore.Audio.AlbumColumns.FIRST_YEAR,
MediaStore.Audio.AlbumColumns.ARTIST};
String sort_order = MediaStore.Audio.AlbumColumns.ALBUM + " ASC";
Cursor acursor = resolver.query
(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
dataColumns,
null, null,
sort_order);
return acursor;
}

Not able to fetch the correct Birthday and Anniversary data from Contact

I am able to fetch other information (Display name,organisation,phone no and email_id) of a contact, but not able to fetch birthday and anniversary of that contact.
Here is the code i am using for birthday. It does fetch the data, but gives me wrong data, i.e repeats the same data for all the contacts.
private String getBDate(String id) {
String bday = null;
ContentResolver cr = getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE };
String where = ContactsContract.Data.MIMETYPE + "= ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE + "="
+ ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] selectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
String sortOrder = null;
Cursor cur = cr.query(uri, projection, where, selectionArgs, sortOrder);
while (cur.moveToNext()) {
bday = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
Log.v("Birthday", bday);
}
cur.close();
return bday;
}
Same is the case with anniversary, here is the code for it. In some case anniversary is not added but it still shows the data from other contact.
private String getAnnv(String id) {
String annv = null;
ContentResolver cr = getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE };
String where = ContactsContract.Data.MIMETYPE + "= ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE + "="
+ ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY;
String[] selectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
// String sortOrder = null;
Cursor cur = cr.query(uri, projection, where, selectionArgs, null);
while (cur.moveToNext()) {
annv = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
Log.v("Anniversary", annv);
}
cur.close();
return annv;
}
you are not using String id perameter in where condition so please check again.
E,g private String getAnnv(String id) function has input for ID but that seems to be not used withing function so please put that ID in condition check and this should work.
e.g
ContactsContract.CommonDataKinds.Event.CONTACT_ID + "= " + ID
AND ContactsContract.Data.MIMETYPE + "= ? AND "

Query Contact members from a specified group?

I need to fetch the members for a specific group in android contacts.
I have the contact group names and their ID's
Can anyone provide me how to query the contacts provider for members in a particular group ?
Try this method:
private Cursor getContacts(String groupID) {
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Data.DISPLAY_NAME
};
String selection = null;
String[] selectionArgs = null;
if(groupID != null && !"".equals(groupID)) {
selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
+ " = ?";
selectionArgs = new String[] { groupID };
}
else
selection = "1) GROUP BY (" + ContactsContract.Data.CONTACT_ID;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC ";
return getContentResolver().query(uri, projection,
selection, selectionArgs, sortOrder);
}
This works on Android 2.3.3 and lower, but doesn't work on Android 4+ and I don't currently know why.
UPD.
Adding custom string parameter "GROUP BY" to SQL query is denied in Android 4+, so I've founded this workaround:
private Cursor getContacts(String groupID) {
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Data.DISPLAY_NAME
};
String selection = null;
String[] selectionArgs = null;
if(groupID != null && !"".equals(groupID)) {
selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
+ " = ?";
selectionArgs = new String[] { groupID };
}
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC ";
Cursor cursor = getContentResolver().query(uri, projection,
selection, selectionArgs, sortOrder);
MatrixCursor result = new MatrixCursor(projection);
Set<Long> seen = new HashSet<Long>();
while (cursor.moveToNext()) {
long raw = cursor.getLong(1);
if (!seen.contains(raw)) {
seen.add(raw);
result.addRow(new Object[] { cursor.getLong(0),
cursor.getLong(1), cursor.getString(2) });
}
}
return result;

Retrieving phone number from contact id : android

I'm trying to get contact data once a contact name has been clicked from my list view. As per the code below, I can log successfully the ID of my contact, but haven't managed to use the ContactsContract to retrieve the data. What's the best way to do this? (have tried Retrieve Contact Phone Number From URI in Android to not much avail)
EDIT 2 : Fixed code, now works
public void onCreate(Bundle savedInstanceState)
{
Log.v(TAG, "Activity State: onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_manager);
mContactList = (ListView) findViewById(R.id.contactList);
populateContactList();
mContactList.setOnItemClickListener(new OnItemClickListener() {
String strid = Long.toString(id);
Cursor result = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts._ID +" = ?", new String[]{strid}, null);
if (result.moveToFirst()) {
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Phone.LABEL},
Data.RAW_CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
new String[] {String.valueOf(strid)}, null);
if(c.moveToFirst()){
int phoneColumn = c.getColumnIndex("data1");
String phoneNumber = c.getString(phoneColumn);
Log.d("DATA",phoneNumber);
}
}
});
}
EDIT 1 : forgot some important stuff. The code is adapted from the ContactManager example from the Android dev site.
/**
* Populate the contact list based on account currently selected in the account spinner.
*/
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
String[] fields = new String[] {
ContactsContract.Data.DISPLAY_NAME
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
fields, new int[] {R.id.contactEntryText});
mContactList.setAdapter(adapter);
}
/**
* Obtains the contact list for the currently selected account.
*
* #return A cursor for for accessing the contact list.
*/
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
Assuming you have a valid contactID, you can do this:
Cursor result = managedQuery(ContactsContract.Contacts.CONTENT_URI, null,
ContactsContract.Contacts._ID +" = ?",
new String[]{contactID}, null);
if (result.moveToFirst()) {
for(int i=0; i< result.getColumnCount(); i++){
Log.i("CONTACTSTAG", result.getColumnName(i) + ": "
+ result.getString(i));
}
}
You will have to change the ContactsContract.Contacts.CONTENT_URI and the where clause to the table that you are querying. The above code will print out a bunch of general info about a contact.

Android get a cursor only with contacts that have an email listed

Friends I want Contacts which have email and also sort in ascending order..
any one know how to get this list and sort..
Please help me and thanks in advance.
I am using this code.
MatrixCursor matCur = new MatrixCursor(new String[] { Contacts._ID,
Contacts.DISPLAY_NAME, "photo_id", "starred" });
Cursor cEmail = WP7Main.this.managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cEmail.moveToFirst();
if (cEmail.moveToFirst())
{
// String name =
// cursor.getString(cursor.getColumnIndexOrThrow(People.NAME));
String contactId = cEmail.getString(cEmail.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = WP7Main.this.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + contactId, null, null);
String emailAddress = "";
while (emails.moveToNext())
{
// This would allow you get several email addresses
if (emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)) != null)
{
String[] columnValues = {
cEmail.getString(cEmail
.getColumnIndex("_id")),
cEmail.getString(cEmail
.getColumnIndex("display_name")),
cEmail.getString(cEmail
.getColumnIndex("photo_id")),
cEmail.getString(cEmail
.getColumnIndex("starred")) };
matCur.addRow(columnValues);
}
}
emails.close();
}
Try this:
/**
* #return A managed cursor of email contacts for the given activity.
*/
public static Cursor buildFilteredEmailCursor(Activity activity) {
final String my_sort_order = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
String my_selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] eproj = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA};
Uri uri = android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI;
return activity.managedQuery(uri, eproj, my_selection, null, my_sort_order);
}
Use this query :
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[]{Data.CONTACT_ID, Data.DISPLAY_NAME, Email.ADDRESS},
Data.MIMETYPE + "=?", new String[] {Email.CONTENT_TYPE}, Data.DISPLAY_NAME /* use Email.ADDRESS if you want to sort it using that*/);

Categories

Resources