I am fetching contacts from android and storing it in a database. Tested it on a emulator and it was working. But when I tested the app on my phone I got duplicate entries of contacts who were using Whatsapp. Below is the code snippet.
class LoadContactAsync extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
Cursor people = getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
"UPPER(" + ContactsContract.Contacts.DISPLAY_NAME
+ ") ASC");
while (people.moveToNext()) {
final String contactId = people.getString(people
.getColumnIndex(ContactsContract.Contacts._ID));
final String contactName = people
.getString(people
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
final String image_uri = people
.getString(people
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
final String hasPhone = people
.getString(people
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ((Integer.parseInt(hasPhone) > 0)) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null,
"UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
while (phones.moveToNext()) {
final String phoneNumber = phones
.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
db.addContact(new Contact(contactName, phoneNumber, image_uri));
}
phones.close();
}
}
people.close();
return null;
}
#Override
protected void onPostExecute(String s) {
pd.dismiss();
showToast("Contacts Added Successfully");
db.close();
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Please Wait...",
"Fetching One Time Contacts", true, false);
}
}
Here is the screenshot
With No Whatsapp installed
With No Whatsapp installed
With Whatsapp Installed
With Whatsapp Installed
Any help will be greatly appreciated.
Thanks
If you don't want to use database to avoid duplicate entries, use below code
private HashMap<String, ContactModel> getContactsList() {
String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Data.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.PHOTO_URI};
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
String lastPhoneName = " ";
if (phones.getCount() > 0) {
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactId = phones.getString(phones.getColumnIndex(ContactsContract.Contacts._ID));
String photoUri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (!name.equalsIgnoreCase(lastPhoneName)) {
lastPhoneName = name;
contactDetail.put(contactId, new ContactModel(contactId, name, phoneNumber, photoUri));
Log.d("getContactsList", name + "---" + phoneNumber + " -- " + contactId + " -- " + photoUri);
}
}
}
phones.close();
return contactDetail;
}
For someone who might face same error.. This did the trick for me.. Make Phone Number column as unique in your database table..
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT UNIQUE," + KEY_IMAGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
Store all contact data's in one array list (which include duplicate),
ArrayList mDetailsArrayList =new ArrayList<>();
then in postExecute remove duplicate entries using method removeDuplicates();
private ArrayList<Contact> removeDuplicate(ArrayList<Contact> contactArrayList){
Set set = new TreeSet(new Comparator() {
#Override
public int compare(Object lhs, Object rhs) {
if (lhs instanceof Contact && rhs instanceof Contact) {
if (((Contact) lhs).getContactName().equalsIgnoreCase(((Contact) rhs).getContactName())) {
return 0;
}
}
return 1;
}
});
set.addAll(contactArrayList);
System.out.println("\nAfter removing duplicates\n");
final ArrayList newList = new ArrayList(set);
System.out.println(set);
return newList;
}
Now this returned array list will hold real data's
Related
I'm trying to get the given name, family name etc of a specific contact on android but can't seem to be able to. I've been banging my head on this for hours, basically if (nameCur.moveNext()) is always false! This code is originally by #perborin (How to get the first name and last name from Android contacts?). Please help!
P.S. I've added <uses-permission android:name="android.permission.READ_CONTACTS"/> in the AndroidManifest, so that is not the problem.
// A contact ID is fetched from ContactList
Uri resultUri = data.getData();
Cursor cont = getContentResolver().query(resultUri, null, null, null, null);
if (!cont.moveToNext()) {
Toast.makeText(this, "Cursor contains no data", Toast.LENGTH_LONG).show();
return;
}
int columnIndexForId = cont.getColumnIndex(ContactsContract.Contacts._ID);
String contactId = cont.getString(columnIndexForId);
// Fetch contact name with a specific ID
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = " + contactId;
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Toast.makeText(this, "Name: " + given + " Family: " + family + " Displayname: " + display, Toast.LENGTH_LONG).show();
}
nameCur.close();
cont.close();
Solved by referring to user3717188 answer at Get first and last name of a contact rather than single display name?.
Cursor phone_cursor = cr.query(ContactsContract.CommonDataKinds.
Phone.CONTENT_URI, null, null, null, null);
while (phone_cursor.moveToNext()) {
try {
int id = Integer.parseInt(phone_cursor.getString(phone_cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
Cursor name_cursor = cr.query(ContactsContract.Data.CONTENT_URI,null,
ContactsContract.Data.CONTACT_ID + " = " + id, null, null);
String name = phone_cursor.getString(phone_cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String first_name ="";
String last_name = "";
while (name_cursor.moveToNext()) {
if(name_cursor.getString(name_cursor.getColumnIndex
(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME))!=null){
first_name = name_cursor.getString(name_cursor.getColumnIndex
(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
last_name = name_cursor.getString(name_cursor.getColumnIndex
(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
}}
name_cursor.close();
String phoneNumber = phone_cursor.getString(phone_cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
} catch (Exception e) {
}
}
phone_cursor.close();
I get null pointer exception at cursor moveToFirst() when retrieving contacts phone number on Lollipop devices but in other OS version it working fine.
Exception occur at pCur.moveToFirst(); under the getContact() method
please see my code:
public class MyService extends Service {
public static Context mContext;
LinkedHashMap<String, String> name = new LinkedHashMap<String, String>();
HashMap<String, String> contactDetails = new HashMap<String, String>();
HashMap<String, Bitmap> image = new HashMap<String, Bitmap>();
private Cursor pCur, contactsCursor;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String[] PROJECTION = { Contacts._ID, Contacts.LOOKUP_KEY,
Contacts.DISPLAY_NAME_PRIMARY, Contacts.PHOTO_THUMBNAIL_URI,
Contacts.SORT_KEY_PRIMARY };
String SELECTION = Contacts.DISPLAY_NAME_PRIMARY + "<>''" + " AND "
+ Contacts.IN_VISIBLE_GROUP + "=1" + " AND "
+ Contacts.HAS_PHONE_NUMBER;
String SORT_ORDER = Contacts.SORT_KEY_ALTERNATIVE;
contactsCursor = getContentResolver().query(Contacts.CONTENT_URI,
PROJECTION, SELECTION, null, SORT_ORDER);
StoreCursor.qcursor = contactsCursor;
Log.e("cur", "cur" + StoreCursor.qcursor.getCount());
getContact();
return START_STICKY;
}
private void getContact() {
Log.e("result cursor", "" + contactsCursor.getCount());
String displayName;
String contactId;
contactsCursor.moveToFirst();
do {
displayName = contactsCursor.getString(2);
contactId = contactsCursor.getString(0);
// Log.e("disName & id", displayName + " "+contactId);
pCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] { contactId }, null);
String cPN = "";
pCur.moveToFirst(); // NullPointerException occur here.
do {
int phoneType = pCur
.getInt(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
switch (phoneType) {
case Phone.TYPE_MOBILE:
cPN = cPN + "(mobile number)" + phoneNumber + "\n";
break;
case Phone.TYPE_HOME:
cPN = cPN + "(home number)" + phoneNumber + "\n";
break;
case Phone.TYPE_WORK:
cPN = cPN + "(work number)" + phoneNumber + "\n";
break;
case Phone.TYPE_OTHER:
cPN = cPN + "(other number)" + phoneNumber + "\n";
break;
default:
break;
}
} while (pCur.moveToNext());
name.put(contactId, displayName);
Log.e("displayName", displayName);
StoreCursor.name = name;
contactDetails.put(contactId, cPN);
StoreCursor.contactDetails = contactDetails;
String photo = contactsCursor.getString(3) + "~";
// Log.e("photo url", photo);
if (photo.length() > 6) {
openPhoto(Long.valueOf(contactId), displayName);
}
} while (contactsCursor.moveToNext());
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
That's an easy one:
If pCur.moveToFirst(); throws a NullPointerException, this means that pCur is null. Since pCur is only set in one place,
pCur = getContentResolver().query(...);
this means that your call to ContentResolver.query returns null.
Now the real question is: Why does ContentResolver.query return null? That's a good question, and I suggest that you ask it as a new question here on SO. Be sure to include all relevant information, i.e.:
which URL are you trying to resolve,
which parameters do you use and where to you get them from,
etc.
Ideally, you should add a minimal complete example to your new question (note that your current code snippet is neither minimal nor complete).
I have made an app in which I need all the contacts available in the phone-book. I display these numbers in a list.The app works fine but some times the app force closes because the cursor returns null.This does not happens always but it happens some times.Now how do I handle this ????
Code
public static JSONArray getAllContactList(Context context) {
Cursor c = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
alAllContacts = new ArrayList<ContactModel>();
while (!(c == null) && c.moveToNext()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String number = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (number.equalsIgnoreCase("1")) {
// Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
// ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = '" + id + "'", null, null);
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
while (phones.moveToNext()) {
String contactName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber = contactNumber.replace("+", "");
if (contactNumber.length() > 10) {
contactNumber = contactNumber.substring(2);
}
// contactNumber.replace("+91", "");
alAllContacts.add(new ContactModel(contactName, contactNumber));
//
}
}
}
c.close();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < alAllContacts.size(); i++) {
jsonArray.put(alAllContacts.get(i).getJSONObject());
}
return jsonArray;
}
the logcat says that i am getting null pointer at this line
while (phones.moveToNext()) {
Also some times i get force close because by dialog is running,So is my code for showing the progress bar correct
public static void showProgress(Context context, String msg, boolean isVisible) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(msg);
progressDialog.setCancelable(false);
}
if (isVisible) {
progressDialog.show();
} else if (isVisible == false) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I use this code for getting all contacts and it does the job.
private static void backupContacts(Context context) {
String[] pCurProjection = new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL,
ContactsContract.CommonDataKinds.Phone.IS_PRIMARY
};
String contactSelection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] contactProjection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
Cursor contactCursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
contactProjection,
contactSelection,
null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
int contactId;
String contactName;
if (null != contactCursor) {
while (contactCursor.moveToNext()) {
contactId = contactCursor.getInt(
contactCursor.getColumnIndex(ContactsContract.Contacts._ID));
contactName = contactCursor.getString(
contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactId + ": " + contactName);
Cursor pCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
pCurProjection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{String.valueOf(contactId)},
null);
if (null != pCur) {
while (pCur.moveToNext()) {
int id = pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone._ID);
String number = (pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
String type = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));//this line returns Null but it does not effect on the code(Does not Throws NullPointerException). if you found fix for it please let me know
int isPrimary = pCur.getInt(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY));
System.out.println(id + ": " + number + "\n" + type + "\n" + isPrimary);
}
pCur.close();
}
}
contactCursor.close();
}
}
if you have any question let me know :)
I'm creating methods to edit a contact's field.
Before editing I'm making sure that those fields do exist and correspond to the company I want to edit, so I make a select and look for if(cursor.moveToFirst()) but it is not going inside the if for some reason I can not understand. I just know that the problem is on my empty Strings as if I remove them the code works fine.
I've downloaded the phones contact database so I know exactly what is in the contacts database. That is why I'm hardcoding the variables.
Here is my code:
public Boolean editRawContactOrganization(String rawContactId, String oldCompany, String oldType, String oldLabel, String oldTitle,
String oldDepartment, String oldJobDescription, String oldSymbol, String oldPhoneticName, String oldLocation,
String newCompany, String newType, String newLabel, String newTitle, String newDepartment, String newJobDescription,
String newSymbol, String newPhoneticName, String newOfficeLocation)
{
final ContentValues cv = new ContentValues();
final String filter = Organization.RAW_CONTACT_ID + "=? AND "
+ Organization.COMPANY + "=? AND "
+ Organization.TYPE_WORK + "=? AND "
+ Organization.LABEL + "=? AND "
+ Organization.TITLE + "=? AND "
+ Organization.DEPARTMENT + "=? AND "
+ Organization.JOB_DESCRIPTION + "=? AND "
+ Organization.SYMBOL + "=? AND "
+ Organization.PHONETIC_NAME + "=? AND "
+ Organization.OFFICE_LOCATION + "=? AND "
+ Data.MIMETYPE + "=?";
oldCompany = "Tone Inc.";
oldType = "2";
oldLabel = "";
oldTitle = "The Big Boss";
oldDepartment = "";
oldJobDescription = "";
oldSymbol = "";
oldPhoneticName = "";
oldLocation = "";
final String[] selectionArgs = new String[] {rawContactId, oldCompany, oldType, oldLabel, oldTitle, oldDepartment, oldJobDescription,
oldSymbol, oldPhoneticName, oldLocation, Organization.CONTENT_ITEM_TYPE};
final String[] projection = new String[] { Organization._ID };
final Cursor cursor = contentResolver.query(Data.CONTENT_URI,
projection,
filter,
selectionArgs,
null);
if(cursor.moveToFirst())
{
Log.d(TAG, "SUCCESS: Organization found! ID: " + cursor.getString(0));
cursor.close();
}
else
{
Log.d(TAG, "ERROR: Organization not found...");
cursor.close();
return false;
}
return false;
}
As you can see, these vars are hard coded with the corresponding values I see on the contacts database I just downloaded from the phone.
oldCompany = "Tone Inc.";
oldType = "2";
oldLabel = "";
oldTitle = "The Big Boss";
oldDepartment = "";
oldJobDescription = "";
oldSymbol = "";
oldPhoneticName = "";
oldLocation = "";
But I always get the ERROR: Organization not found... output on logcat
Can anyone point me to where is the error?
Here is a working example, if I uncoment the commented code I get the not found output (the same problem as above). Same pattern as above, the commented column has no value inside. Even when I'm sending and empty string why doesn't is match empty with empty?
public Boolean editRawContactWebsite(String rawContactId, String oldWebsite, String oldType, String oldLabel,
String newWebsite, String newType, String newLabel)
{
final ContentValues cv = new ContentValues();
final String filter = Website.RAW_CONTACT_ID + "=? AND "
+ Website.URL + "=? AND "
+ Website.TYPE + "=? AND "
//+ Website.LABEL + "=? AND "
+ Data.MIMETYPE + "=?";
oldWebsite = "www.sitr.com";
oldType = "7";
oldLabel = "";
final String[] selectionArgs = new String[] {rawContactId, oldWebsite, oldType, /*oldLabel,*/ Website.CONTENT_ITEM_TYPE};
final String[] projection = new String[] { Website._ID };
final Cursor cursor = contentResolver.query(Data.CONTENT_URI,
projection,
filter,
selectionArgs,
null);
if(cursor.moveToFirst())
{
Log.d(TAG, "SUCCESS: website found! ID: " + cursor.getString(0));
cursor.close();
}
else
{
Log.d(TAG, "ERROR: website not found...");
cursor.close();
return false;
}
return false;
}
I fixed this problem by passing an ID corresponding to the line I want to edit in the contacts database.
In my application I need to give user opportinity to see/edit all available fields of ContactsContract.
How should I get/see all available fields - including any custom ones?
First get all of the names of people that exist in your phone:
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC");
while (phones.moveToNext()) {
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
namelist.add(name);
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
number_list.add(phoneNumber);
detaillist.put(name, phoneNumber);
}
phones.close();
}
Now get contact id and get other information like phone number, email id, address, organization by using contact id:
protected void get_UserContactId(String item_clicked)
{
System.out.println("i m in fincution contact id");
ContentResolver localContentResolver = this.getContentResolver();
Cursor contactLookupCursor =
localContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(item_clicked)),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
try {
while(contactLookupCursor.moveToNext()){
contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
user_contact_id = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
System.out.println("contatc id id"+user_contact_id);
}
}
finally {
contactLookupCursor.close();
}
}
protected void get_UserEmail(String item_clicked)
{
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + user_contact_id, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
user_email_id = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String user_email_type=emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("the email type"+user_email_type);
System.out.println("email address might be"+emailAddress);
contact_attribute_type.add(EMAIL_TYPE[(Integer.parseInt(user_email_type))-1]);
contact_attribute_value.add(user_email_id);
}
emails.close();
}
protected void get_UserNumber(String item_clicked) {
// TODO Auto-generated method stub
final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.STARRED,
ContactsContract.Contacts.TIMES_CONTACTED,
ContactsContract.Contacts.CONTACT_PRESENCE,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" +item_clicked+ "\" )";
Cursor c = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
this.startManagingCursor(c);
if (c.moveToNext())
{
String id = c.getString(0);
ArrayList<String> phones = new ArrayList<String>();
Cursor pCur = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while (pCur.moveToNext())
{
phones.add(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
user_number=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String number_type=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
System.out.println("the number type---"+number_type);
System.out.println("user no. in share is"+user_number);
contact_attribute_type.add(PHONE_TYPE[(Integer.parseInt(number_type))-1]);
contact_attribute_value.add(user_number);
// Log.i("", name_to_search+ " has the following phone number "+ pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
pCur.close();
}
}
protected String get_UserAddress() {
// TODO Auto-generated method stub
try {
System.out.println(" i m in user address");
Cursor address = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + client_contact_id, null, null);
while (address.moveToNext()) {
// This would allow you get several email addresses
user_home_address = address.getString(
address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA));
String user_address_type=address.getString(
address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
System.out.println("the user address type"+user_address_type);
System.out.println(" address might be"+user_home_address);
contact_attribute_type.add(ADDRESS_TYPE[(Integer.parseInt(user_address_type))-1]);
contact_attribute_value.add(user_home_address);
}
address.close();
}
catch(Exception e)
{
System.out.println("this exception due to website"+e);
}
return(user_home_address);
}
protected void get_UserWebsite() {
// TODO Auto-generated method stub
try{
Cursor websiteNameCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] {Website.URL}, ContactsContract.Data.CONTACT_ID + " = " + user_contact_id + " AND ContactsContract.Data.MIMETYPE = '"
+ ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE
+ "'",null,null);
websiteNameCursor.moveToNext();
user_website=(websiteNameCursor.getString(websiteNameCursor.getColumnIndex(Website.URL)));
System.out.println("this is my website"+(websiteNameCursor.getString(websiteNameCursor.getColumnIndex(Website.URL))));
contact_attribute_type.add("Website");
contact_attribute_value.add(user_website);
}
catch(Exception e)
{
user_website=null;
System.out.println("this website is"+user_website);
System.out.println("this exception in website"+e);
}
}
protected void get_UserOrganization() {
// TODO Auto-generated method stub
try{
Cursor organizationNameCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] {Organization.COMPANY}, ContactsContract.Data.CONTACT_ID + " = " + user_contact_id + " AND ContactsContract.Data.MIMETYPE = '"
+ ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE
+ "'",null,null);
organizationNameCursor.moveToNext();
user_company=organizationNameCursor.getString(organizationNameCursor.getColumnIndex(Organization.COMPANY));
// String user_company_type=organizationNameCursor.getString(organizationNameCursor.getColumnIndex(Organization.TYPE));
// System.out.println("the company type "+user_company_type);
System.out.println("this is my organization"+user_company);
contact_attribute_type.add("Company");
contact_attribute_value.add(user_company);
}
catch(Exception e)
{
user_company=null;
System.out.println("user company name is"+user_company);
System.out.println("this exception in org"+e);
}
}
}
By doing this you can get all the fields of contacts-contract.
This logs the name and value of all columns in all contact rows. Tested on Galaxy S6 with native contacts app. I needed it to find the column name that is used for custom SMS notification sound (sec_custom_alert).
private void enumerateColumns() {
Cursor cursor = getApplicationContext().getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
for(int i=0; i<cursor.getColumnCount();i++)
{
Log.d("myActivity", cursor.getColumnName(i) + " : " + cursor.getString(i));
}
} while (cursor.moveToNext());
cursor.close();
}
}