How to get the contact group id or name? - java

I can't get the group name under which the contact is stored. I can get whether it is added in any group as boolean value( IN_VISIBLE_GROUP).I have no idea how to get the group name or id.
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext())
{
id = cur.getString(cur
.getColumnIndex(BaseColumns._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String group = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.IN_VISIBLE_GROUP));
i have tried using ContactsContract.Groups and ContactsContract.Groups and ContactsContract.CommonDataKinds.GroupMembership but that is not the solution.

This is a full version of how to get the group id by its title. Basically it iterates all groups and compare titles to find its id.
private String getGroupId(String groupTitle) {
Cursor cursor =getContentResolver().query(ContactsContract.Groups.CONTENT_URI,new String[]{ContactsContract.Groups._ID,ContactsContract.Groups.TITLE}, null, null, null);
cursor.moveToFirst();
int len = cursor.getCount();
String groupId = null;
for (int i = 0; i < len; i++) {
String id = cursor.getString(cursor.getColumnIndex(Groups._ID));
String title = cursor.getString(cursor.getColumnIndex(Groups.TITLE));
if (title.equals(groupTitle)) {
groupId = id;
break;
}
cursor.moveToNext();
}
cursor.close();
return groupId;
}

Please change
ContentResolver cr = this.getContentResolver();
to
Uri groupURI = ContactsContract.Data.CONTENT_URI;
Cursor cur = cr.query(groupURI , null, null, null, null);
// Now you can get group ID from cursor
String groupRowId = cur.getString (cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));

public Integer getGroupId(String groupTitle) {
String[] PROJECTION = {ContactsContract.Groups._ID};
String SELECTION = ContactsContract.Groups.TITLE + "=?";
try (Cursor cursor = mContentResolver.query(ContactsContract.Groups.CONTENT_URI,
PROJECTION, SELECTION, new String[]{groupTitle}, null)) {
if (cursor.getCount()>0){
cursor.moveToFirst();
Integer id= cursor.getInt(0);
return id;
}else
return 0;
}
}

Related

CursorIndexOutOfBoundsException When trying to export details from a database (Android Studio) [duplicate]

I'm trying to read all the contacts using RawContacts.entityIterator but I'm seeing this error:
android.database.CursorIndexOutOfBoundsException: Index -1 requested
Following is my code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Contacts.CONTENT_URI,
null, null, null, null);
String id = cur.getString(cur.getColumnIndex(Contacts._ID));
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
final Uri uri = RawContactsEntity.CONTENT_URI;
final String selection = Data.CONTACT_ID + "=?";
final String[] selectionArgs = new String[] {id};
final Map<String, List<ContentValues>> contentValuesListMap =
new HashMap<String, List<ContentValues>>();
EntityIterator entityIterator = null;
entityIterator = RawContacts.newEntityIterator(cr.query(
uri, null, selection, selectionArgs, null));
while (entityIterator.hasNext()) {
Entity entity = entityIterator.next();
for (NamedContentValues namedContentValues : entity.getSubValues()) {
ContentValues contentValues = namedContentValues.values;
String key = contentValues.getAsString(Data.MIMETYPE);
if (key != null) {
List<ContentValues> contentValuesList =
contentValuesListMap.get(key);
if (contentValuesList == null) {
contentValuesList = new ArrayList<ContentValues>();
contentValuesListMap.put(key, contentValuesList);
}
contentValuesList.add(contentValues);
}
}
}
Log.i(tag, "Contact index=" + id);
}
}
Can somebody please tell me what's wrong with my code.
After you execute query, you must call cur.moveToFirst()...
Try this
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Contacts.CONTENT_URI,
null, null, null, null);
if(cur != null && cur.moveToFirst())
{
String id = cur.getString(cur.getColumnIndex(Contacts._ID));
if (cur.getCount() > 0) {
...
It is not required to call moveToFirst but to ensure that you moved to any of the returned rows before accessing a value (see moveToLast(), moveToPosition(int position), ... ).
So this one:
Cursor cur = cr.query(Contacts.CONTENT_URI, null, null, null, null);
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(Contacts._ID));
final Uri uri = RawContactsEntity.CONTENT_URI;
would work as well - or even better, because there is an issue with the accepted answer, if you continue with ...
while (cur.moveToNext()) {
after
if (cur.getCount() > 0) {
It would skip the first row, what might not be obvious.

How to fetch all contacts using cursor and store it in strings to store them in firebase realtime database

fetch all contacts using cursor and store it in strings to store them in firebase realtime database
ArrayList<String> contactData=new ArrayList();
ContentResolver cr = getContentResolver();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
try{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
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));
Firebase mRefchild = mRef.child(name);
mRefchild.setValue(phoneNumber);
}
phones.close();
to get all Constact List
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
To save list or store list to firebase
Firebase ref = new Firebase("<my-firebase-app>/names"):
List nameList = new ArrayList<Type>(Arrays.asList(names));
// Now set value with new nameList
ref.setValue(nameList)

get Home Location from a contact in Contacts List Android?

i use the following code for get all Contacts:
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact_Details dt = new Contact_Details(name, number, UIDD);
dataArray.add(dt);
}
pCur.close();
}
}
}
cur.close();
}
now i want to get the home location from Contacts. what can i do now. home location is shown in the following image.
use this code to retrieve address from contact
Cursor pCur2 = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur2.moveToNext())
{
String address = pCur2.getString(pCur2.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
Log.d("tag", "Address: "+address);
}
pCur2.close();
this retrieve both phone and address
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext())
{
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("tag", "PhoneNumber: "+number);
}
pCur.close();
//get address of the phone
Cursor pCur2 = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur2.moveToNext())
{
String address = pCur2.getString(pCur2.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
Log.d("tag", "Address: "+address);
}
pCur2.close();
}
}
}
cur.close();
}

Android Contacts - Get Phone number

I'm trying to get all phone numbers of a contact in Android. My code looks like this:
ContentResolver cr = context.getContentResolver();
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
String selection = ContactsContract.Data.CONTACT_ID + "=" + contactId;
Cursor nameCur = cr.query(ContactsContract.Data.CONTENT_URI, projection, selection, null, null);
while (nameCur.moveToNext()) {
String contact = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
In principle, it works but the variable "contact" sometimes has values like "null", "1", "4" or "phonenumber#whatsapp". How can I really only get the phone numbers without these stupid WhatsApp Id strings?
You can also check what is contact: phone number or something else:
public static boolean isPhoneNumberValid(CharSequence phone) {
return !(TextUtils.isEmpty(phone)) && Patterns.PHONE.matcher(phone).matches();
}
i use below code and its work, see this:
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
cursor.moveToFirst();
// data = new String[cursor.getCount()][12];
if (cursor.getCount() > 0) {
do {
try {
contactId = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
Uri contactUri = ContentUris.withAppendedId(
Contacts.CONTENT_URI,
Long.parseLong(contactId));
Uri dataUri = Uri.withAppendedPath(contactUri,
Contacts.Data.CONTENT_DIRECTORY);
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId,
null, null);
if (phones.getCount() > 0) {
ContactClass info = new ContactClass();
info.setid(contactId);
try {
Cursor nameCursor = getContentResolver()
.query(dataUri,
null,
Data.MIMETYPE + "=?",
new String[] { StructuredName.CONTENT_ITEM_TYPE },
null);
nameCursor.moveToFirst();
do {
String firstName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA2));
String lastName = "";
String displayname = cursor
.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME_ALTERNATIVE));
if (!firstName.equals(displayname)) {
lastName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA3));
}
if (firstName.equals(null)
&& lastName.equals(null)) {
info.setfirstname("unknown name");
} else if (firstName.equals(null)) {
info.setlastname(lastName);
} else if (lastName.equals(null)) {
info.setfirstname(firstName);
} else {
info.setfirstname(firstName);
info.setlastname(lastName);
}
} while (nameCursor.moveToNext());
nameCursor.close();
} catch (Exception e) {
}
}
phones.close();
}
catch (Exception t) {
}
} while (cursor.moveToNext());
cursor.close();

how to restore contacts?

I'm trying to add contact to contacts database with a specific contact id (i'm using a vcf file to get contact's details), the contact id is saved in the file name (Dani_13) and I need to add this contact to its original entry in contacts . i've been using the code bellow but it's not working :
String [] s = (vcard_file.getName()).split(Pattern.quote("_"));
String [] s2 = s[(s.length)-1].split(Pattern.quote("."));
// int rawContactInsertIndex=ops.size();
int id = Integer.getInteger(s2[0]);
ops.add(ContentProviderOperation
.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, id)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, null)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, city)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, state)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, zipcode)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, country)
//.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK)
.build());
try this one:
ContentResolver cr = getContext().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
}
}
worked for me.

Categories