Hari Prasad Hari Prasad -4 years ago 42
Android Question

getting contacts from a specified group in android

I'm trying to get contacts from a specific group of known id.i'm able to get group id and contact names in that group.but i'm unable to get contact numbers.tried some solutions from google search, but every time i'm getting phone number same as group id , if i query group for phone numbers and contact names using Phone.number , Phone.DISPLAY_NAME.if i use below method i'm getting error
please help me to figure out whats wrong in my code.

Code :

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.group_contacts);
addGroups = (Button) findViewById(R.id.selectGroup);

groupAdapter = new SimpleCursorAdapter(getApplicationContext(),
android.R.layout.select_dialog_singlechoice, GroupCursor(),
new String[] { ContactsContract.Groups.TITLE },
new int[] { android.R.id.text1 });
setListAdapter(groupAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

addGroups.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(myGroups.this, Main.class);
Bundle carry = new Bundle();
carry.putStringArrayList("numbers", cNumbers);
carry.putStringArrayList("name", cNames);
intent.putExtras(carry);
setResult(RESULT_OK, intent);
finish();
}
});

}

private Cursor GroupCursor() {
// TODO Auto-generated method stub
String[] projection = { ContactsContract.Groups.TITLE,
ContactsContract.Groups._ID };
Cursor gCursor = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI, projection, null, null,
ContactsContract.Groups.TITLE);

// int idcolumn = gCursor.getColumnIndex(ContactsContract.Groups._ID);
// String id = gCursor.getString(idcolumn);

// Log.d(E, "group id : " + id );
return gCursor;

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Log.d(E, "id : " + id);
String groupId = Long.toString(id);

String[] cProjection = { Phone.NUMBER, Phone.DISPLAY_NAME ,Contacts.DISPLAY_NAME, Contacts._ID};

Cursor groupCursor = getContentResolver().query(Data.CONTENT_URI,
cProjection,
CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?",
new String[]{groupId}, null);
if (groupCursor != null) {
groupCursor.moveToFirst();
do {

int nameCoumnIndex = groupCursor
.getColumnIndex(Phone.DISPLAY_NAME);

String name = groupCursor.getString(nameCoumnIndex);

String cId = groupCursor.getString(groupCursor.getColumnIndex(Contacts._ID));

Cursor numberCursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, Phone._ID +"="+cId, null, null);
numberCursor.moveToFirst();
int numberColumnIndex = numberCursor
.getColumnIndex(Phone.NUMBER);
Log.d(E, "numberindex : " + numberColumnIndex);

String number = numberCursor.getString(numberColumnIndex);

cNumbers.add(number);

Log.d(E, "contact " + name + ":" + number);

cNames.add(name);
} while (groupCursor.moveToNext());
}
}
}


Log :

09-04 17:59:24.943: D/dalvikvm(18084): GC_EXTERNAL_ALLOC freed 23K, 48% free 2844K/5379K, external 1032K/1039K, paused 24ms
09-04 17:59:26.054: D/(18084): id : 14
09-04 17:59:26.074: D/(18084): numberindex : 0
09-04 17:59:26.074: D/AndroidRuntime(18084): Shutting down VM
09-04 17:59:26.074: W/dalvikvm(18084): threadid=1: thread exiting with uncaught exception (group=0x40015568)
09-04 17:59:26.084: E/AndroidRuntime(18084): FATAL EXCEPTION: main
09-04 17:59:26.084: E/AndroidRuntime(18084): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.database.CursorWrapper.getString(CursorWrapper.java:135)
09-04 17:59:26.084: E/AndroidRuntime(18084): at hm.swarna.groupsms.myGroups.onListItemClick(myGroups.java:117)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.widget.ListView.performItemClick(ListView.java:3535)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1827)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.os.Handler.handleCallback(Handler.java:587)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.os.Handler.dispatchMessage(Handler.java:92)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.os.Looper.loop(Looper.java:130)
09-04 17:59:26.084: E/AndroidRuntime(18084): at android.app.ActivityThread.main(ActivityThread.java:3703)
09-04 17:59:26.084: E/AndroidRuntime(18084): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 17:59:26.084: E/AndroidRuntime(18084): at java.lang.reflect.Method.invoke(Method.java:507)
09-04 17:59:26.084: E/AndroidRuntime(18084): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
09-04 17:59:26.084: E/AndroidRuntime(18084): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
09-04 17:59:26.084: E/AndroidRuntime(18084): at dalvik.system.NativeStart.main(Native Method)
09-04 17:59:27.556: I/Process(18084): Sending signal. PID: 18084 SIG: 9

Answer Source

Try to use following code in your onListItemClick method:

long groupId = id;
    String[] cProjection = { Contacts.DISPLAY_NAME, GroupMembership.CONTACT_ID };

    Cursor groupCursor = getContentResolver().query(
            Data.CONTENT_URI,
            cProjection,
            CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
                    + ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
                    + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
            new String[] { String.valueOf(groupId) }, null);
    if (groupCursor != null && groupCursor.moveToFirst())
    {
        do
        {

            int nameCoumnIndex = groupCursor.getColumnIndex(Phone.DISPLAY_NAME);

            String name = groupCursor.getString(nameCoumnIndex);

            long contactId = groupCursor.getLong(groupCursor.getColumnIndex(GroupMembership.CONTACT_ID));

            Cursor numberCursor = getContentResolver().query(Phone.CONTENT_URI,
                    new String[] { Phone.NUMBER }, Phone.CONTACT_ID + "=" + contactId, null, null);

            if (numberCursor.moveToFirst())
            {
                int numberColumnIndex = numberCursor.getColumnIndex(Phone.NUMBER);
                do
                {
                    String phoneNumber = numberCursor.getString(numberColumnIndex);
                    Log.d("your tag", "contact " + name + ":" + phoneNumber);
                } while (numberCursor.moveToNext());
                numberCursor.close();
            }
        } while (groupCursor.moveToNext());
        groupCursor.close();
    }

You need to specify mimetype when querying for contacts, which belong to specified group. And because single contact can have multiple phone numbers, you may need to query all of them.

EDIT: To get all groups with at least one contact with phone number you can use following query:

ContentResolver cr = getContentResolver();
Uri groupsUri = ContactsContract.Groups.CONTENT_SUMMARY_URI;
String where = "((" + ContactsContract.Groups.GROUP_VISIBLE + " = 1) AND (" 
                + ContactsContract.Groups.SUMMARY_WITH_PHONES + "!= 0))";
Cursor cursor = cr.query(groupsUri, null, where, null, null);

As for getting contacts with phone number from a specified group - I don't know simple solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download