I am trying to export contact from my application to the Android's default contact list. I am using an intent to insert the contact details by launching the contact activity. The contact activity pre-populate most of the intent data in the form, but It is not able to populate the name of the contact. Here is my code for populating the intent data.
ArrayList<ContentValues> data = new ArrayList<>();
if (!contactDetails.getName().isEmpty()) {
ContentValues rowName = new ContentValues();
rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
rowName.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDetails.getName());
data.add(rowName);
}
if (!contactDetails.getCompany().isEmpty()) {
ContentValues rowCompany = new ContentValues();
rowCompany.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
rowCompany.put(ContactsContract.CommonDataKinds.Organization.COMPANY, contactDetails.getCompany());
data.add(rowCompany);
}
if (!contactDetails.getPhone().isEmpty()) {
ContentValues rowPhone = new ContentValues();
rowPhone.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
rowPhone.put(ContactsContract.CommonDataKinds.Phone.NUMBER, contactDetails.getPhone());
data.add(rowPhone);
}
ContentValues rowEmail = new ContentValues();
rowEmail.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
rowEmail.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_MOBILE);
rowEmail.put(ContactsContract.CommonDataKinds.Email.LABEL, "Work");
rowEmail.put(ContactsContract.CommonDataKinds.Email.ADDRESS, contactDetails.getEmail());
data.add(rowEmail);
Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
intent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, data);
startActivity(intent);
Here is the screen shot. Notice that the name field is empty, even when intent has the data.
I feel that I am not providing the right value for the following lines.
rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
rowName.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDetails.getName());
I tried the NickName field and it does work. example code.
if (!contactDetails.getName().isEmpty()) {
ContentValues rowName = new ContentValues();
rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
rowName.put(ContactsContract.CommonDataKinds.Nickname.NAME, contactDetails.getName());
data.add(rowName);
}
But not sure why it is not able to successfully display the name. Am i missing something here?
Try this its working for me ,and let me inform if you are facing still any issue .Here there are five fields for user to insert data , you can modify this as per ur need.
This is for adding new contact
// Creating a button click listener for the "Add Contact" button
OnClickListener addClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to Name EditText
EditText etName = (EditText) findViewById(R.id.et_name);
// Getting reference to Mobile EditText
EditText etMobile = (EditText) findViewById(R.id.et_mobile_phone);
// Getting reference to HomePhone EditText
EditText etHomePhone = (EditText) findViewById(R.id.et_home_phone);
// Getting reference to HomeEmail EditText
EditText etHomeEmail = (EditText) findViewById(R.id.et_home_email);
// Getting reference to WorkEmail EditText
EditText etWorkEmail = (EditText) findViewById(R.id.et_work_email);
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert display name in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, etName.getText().toString())
.build());
// Adding insert operation to operations list
// to insert Mobile Number in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etMobile.getText().toString())
.withValue(Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
.build());
// Adding insert operation to operations list
// to insert Home Phone Number in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etHomePhone.getText().toString())
.withValue(Phone.TYPE, Phone.TYPE_HOME)
.build());
// Adding insert operation to operations list
// to insert Home Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etHomeEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_HOME)
.build());
// Adding insert operation to operations list
// to insert Work Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etWorkEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_WORK)
.build());
try{
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
}catch (RemoteException e) {
e.printStackTrace();
}catch (OperationApplicationException e) {
e.printStackTrace();
}
}
This is for display contact list
OnClickListener contactsClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Creating an intent to open Android's Contacts List
Intent contacts = new Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);
// Starting the activity
startActivity(contacts);
}
};
This are the permissions you need to set in side Manifest
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
I fixed this problem by just adding the following line just before startActivity() method call.
intent.putExtra(ContactsContract.Intents.Insert.NAME, contactDetails.getName());
You can use cursor to fetch contacts from device.
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\nEmail:" + email);
}
emailCursor.close();
}
output.append("\n");
}
System.out.println(output);
}
}
Related
I am trying to listen to the changes of Contacts. So I tried with one contact first. I have registered a Contact with my app ACCOUNT_TYPE. And trying to listen changes of that particular contact only. whenever there is a change in the Contact ContactsContract.RawContacts.VERSION should get incremented and ContactsContract.RawContacts.DIRTY should become 1. but nothing is getting changed. I am modifying contact in default phone contacts app.
Here is how I am registering contact
ContactsManager.addContact(this,new MyContact("1000","961820018","sandwitch"));
addContact Code:
public static void addContact(Context context,MyContact contact){
ContentResolver resolver = context.getContentResolver();
boolean mHasAccount = isAlreadyRegistered(resolver, contact.Id);
if(mHasAccount){
Log.d("Contact already","there");
} else {
Log.d("new Contact","Adding");
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// insert account name and account type
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.RawContacts.CONTENT_URI, true))
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, Constants.ACCOUNT_NAME)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, Constants.ACCOUNT_TYPE)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
.build());
// insert contact number
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI, true))
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.number)
.build());
// insert contact name
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI, true))
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contact.name)
.build());
// insert mime-type data
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI, true))
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, MIMETYPE)
.withValue(ContactsContract.Data.DATA1, 12345)
.withValue(ContactsContract.Data.DATA2, "user")
.withValue(ContactsContract.Data.DATA3, "MyData")
.build());
try {
resolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this is how I am reading the changes with check VERSION
private void readUpdate(){
Cursor cursor = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.VERSION, ContactsContract.RawContacts.CONTACT_ID,ContactsContract.RawContacts.ACCOUNT_TYPE},
ContactsContract.RawContacts.ACCOUNT_TYPE+"=? ",
new String[]{String.valueOf(Constants.ACCOUNT_TYPE)},
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));
String version = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.VERSION));
String type = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
if(id!=null && dirty!=null&& type!=null){
Log.d("Upadte version",version);
Log.d("Update ACCountid",id);
Log.d("Update type", type);
Cursor cur = mContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
new String[]{String.valueOf(id)},
null);
if(cur!=null && cur.getCount()>0) {
cur.moveToFirst();
while(!cur.isAfterLast()){
String name = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("Update Name", name);
Log.d("Update Number", number);
/* ContactsManager.updateContact(getContext(), id, name, number);
CV.clear();
CV.put(DBconstants.TableConstants.PHONE_NUMBER, number);
CV.put(DBconstants.TableConstants.C_CONTACT_NAME, name);
DB.updateInformation(DB, DBconstants.TableConstants.TABLE_CONTACTS, CV, DBconstants.TableConstants.C_ID, id);
CV.clear();
*/ cur.moveToNext();
}
cur.close();
}else{
Log.d("update", "nullinvalues");
}
}else{
Log.d("update", "nullvalues");
}
cursor.moveToNext();
}
cursor.close();
}else {
Log.d("update", "nullcursor");
}
}
I want to get saved contact id and i used following way to retrieve it but the problem is it's returning the wrong id.
public static String addContact(FragmentActivity activity, String displayname, String mobilenumber, String homeemail) {
String DisplayName = displayname;
String MobileNumber = mobilenumber;
String homeemailID = homeemail;
int contactID = 0;
ArrayList<ContentProviderOperation> contentProviderOperation = new ArrayList<ContentProviderOperation>();
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
// ------------------------------------------------------ Names
if (DisplayName != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
}
// ------------------------------------------------------ Mobile Number
if (MobileNumber != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
}
// ------------------------------------------------------ homeEmail
if (homeemailID != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, homeemailID)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME).build());
}
// Asking the Contact provider to create a new contact
try {
// activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
// contentProviderOperation);
ContentProviderResult[] res = activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
Uri myContactUri = res[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash + 1, length));
} catch (Exception e) {
e.printStackTrace();
}
return contactID;
}
I think it passing the wrong contact data uri.Please help me to get correct contact id.
Try this way:
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if (cursor.moveToFirst()) {
// Get values from contacts database:
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
You don't need to get the id in this way. There's a getLastPathSegment() method in Uri class. Use this instead
Uri myContactUri = res[0].uri;
contactID = Ineger.parseInt(myContactUri.getLastPathSegment());
Other than that, this is the right way to get saved contact id.
I am saving a contact by this code
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
...
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, accountType)
.withValue(RawContacts.ACCOUNT_NAME, accountName)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.GIVEN_NAME, linkname1)
.withValue(StructuredName.FAMILY_NAME, linkname2)
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
After saving the contact, I need to get the _ID field so that I can fetch that contact from the contact book for editing. How can I get the id after saving?
Thanks in advance
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Uri myContactUri = res[0].uri;
int contactID = Integer.parseInt(myContactUri.getLastPathSegment());
Here you go. Get the contact id for the number( ´phnumber` ) from the contacts
String[] projection = new String[]{Contacts._ID};
Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,Uri.encode(phnumber));
Cursor c = getContentResolver().query(contactUri, projection,
null, null, null);
if (c.moveToFirst()) {
long contactId=c.getColumnIndex(Contacts._ID);
c.close();
}
I have built an android app. It will get all contacts (1000 contact) from default address book (of my phone). And then, I show all of them on list view (of my app). BUT, I spend about 13s to load and display on list view. In my code below, I used 3 commands to query: Name, Phone Number and Company of each contact. I think this is the reason why my app which spend too much time to load and display data on listview.
I have 2 questions:
How to get all information of an contact in android by using only 1 SQLite command?
Is there any ways to load and display data onto listview faster???
This is code to query: name, phone no, company of a contact. The result of the query will be stored into a cursor. And then I use the cursor to set listAdapter.
public void addNewContacts(String name, String phone, String com){
String DisplayName = name;
String MobileNumber = phone;
String company = com;
String jobTitle = "Engineer";
ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();
ops.add(ContentProviderOperation.newInsert(
ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
//------------------------------------------------------ Names
if (DisplayName != null) {
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
DisplayName).build());
}
//------------------------------------------------------ Mobile Number
if (MobileNumber != null) {
ops.add(ContentProviderOperation.
newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
}
//------------------------------------------------------ Organization
if (!company.equals("") && !jobTitle.equals("")) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
.build());
}
// Asking the Contact provider to create a new contact
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("ERROR: ", e.getMessage());
}
}
I don't think so you can, or it should be something complicated.
Before fetch any info i need validate if Name exists at least.
Here is code I used:
public class ContactListControl {
/** be sure that final fields equal to input_display_name */
private final static String NAME = "name";
private final static String GMAIL = "gmail";
private final static String PHONE = "phone";
private ContactListControl(){}
public static void onGetContactInfo(Intent data, Context context, List<InputView> inputViewList) {
Map<String, String> contactDataMap = new HashMap<String, String>();
ContentResolver cr = context.getContentResolver();
Uri contactData = data.getData();
//Cursor cursor = managedQuery(contactData, null, null, null, null);
Cursor cursor = cr.query(contactData, null, null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
contactDataMap.put(NAME, (name != null)?name:"");
if (Integer.parseInt(cursor.getString(
cursor.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.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactDataMap.put(PHONE, (number != null)?number:"");
break; // ? we want only 1 value
}
pCur.close();
}
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
contactDataMap.put(GMAIL, (email != null)?email:"");
break;// ? we want only 1 value
}
emailCur.close();
cursor.close();
Log.d("activity result","onActivityResult - got contact: "+contactDataMap.get(NAME) + "; " + contactDataMap.get(GMAIL) + "; " + contactDataMap.get(PHONE));
InputView outputViewName = getInputputViewByDisplayName(NAME, inputViewList);
String tempName = onGetContactInfoAppend(outputViewName, contactDataMap.get(NAME));
outputViewName.setValue(tempName);
InputView outputViewGmail = getInputputViewByDisplayName(GMAIL, inputViewList);
String tempGmail = onGetContactInfoAppend(outputViewGmail, contactDataMap.get(GMAIL));
outputViewGmail.setValue(tempGmail);
InputView outputViewPhone = getInputputViewByDisplayName(PHONE, inputViewList);
String tempPhone = onGetContactInfoAppend(outputViewPhone, contactDataMap.get(PHONE));
outputViewPhone.setValue(tempPhone);
}
private static String onGetContactInfoAppend(InputView outputView, String contactData) {
if(contactData == null){
contactData = "";
}
String temp = outputView.getValue();
//if(!"".equals(contactData)){
if(!"".equals(temp)){
temp = temp + " | ";
}
temp = temp + contactData;
//}
return temp;
}
private static InputView getInputputViewByDisplayName(String displayName, List<InputView> inputViewList) {
for (InputView inputView : inputViewList){
if (inputView.getDisplayName().equals(displayName)){
return inputView;
}
}
return null;
}
}
I am new to android.I need phone contacts to be displayed in my application.The problem I face here is google contacts are also coming with the phone contacts in my application.I don't know how to filter this problem.I need to display only my phone contacts.Please help me.
Thanks in advance
list = new ArrayList<contactlist>();
adptr = new customcontactadptr(this, R.layout.listcontactitem, list);
Uri uri = ContactsContract.Contacts.CONTENT_URI;
ContentResolver cr = getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = cr.query(uri, null, null, null, sortOrder);
if(cur.getCount() > 0)
{
cur.moveToFirst();
do
{
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
String contactid = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
contactlist con = new contactlist();
nme = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("contactid",contactid);
String status = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.CONTACT_STATUS));
Long statuslabel = cur.getLong(cur.getColumnIndexOrThrow(ContactsContract.Contacts.CONTACT_STATUS_LABEL));
if(status!=null)
{
Log.e("status", status);
}
else if(statuslabel!=null)
{
Log.e("status label", Long.toString(statuslabel));
}
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{contactid}, null);
pCur.moveToFirst();
do
{
int phone_type = pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if(phone_type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
{
no = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("Name",nme);
Log.e("Number",no);
con.setchecked(false);
con.setname(nme);
con.setno(n);
list.add(con);
adptr.notifyDataSetChanged();
}
}while (pCur.moveToNext());
pCur.close();
}
}while(cur.moveToNext());
}
setListAdapter(adptr);
Here is the sample code ....
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating a button click listener for the "Add Contact" button
OnClickListener addClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to Name EditText
EditText etName = (EditText) findViewById(R.id.et_name);
// Getting reference to Mobile EditText
EditText etMobile = (EditText) findViewById(R.id.et_mobile_phone);
// Getting reference to HomePhone EditText
EditText etHomePhone = (EditText) findViewById(R.id.et_home_phone);
// Getting reference to HomeEmail EditText
EditText etHomeEmail = (EditText) findViewById(R.id.et_home_email);
// Getting reference to WorkEmail EditText
EditText etWorkEmail = (EditText) findViewById(R.id.et_work_email);
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert display name in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, etName.getText().toString())
.build());
// Adding insert operation to operations list
// to insert Mobile Number in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etMobile.getText().toString())
.withValue(Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
.build());
// Adding insert operation to operations list
// to insert Home Phone Number in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etHomePhone.getText().toString())
.withValue(Phone.TYPE, Phone.TYPE_HOME)
.build());
// Adding insert operation to operations list
// to insert Home Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etHomeEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_HOME)
.build());
// Adding insert operation to operations list
// to insert Work Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etWorkEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_WORK)
.build());
try{
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
}catch (RemoteException e) {
e.printStackTrace();
}catch (OperationApplicationException e) {
e.printStackTrace();
}
}
};
// Creating a button click listener for the "Add Contact" button
OnClickListener contactsClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Creating an intent to open Android's Contacts List
Intent contacts = new Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);
// Starting the activity
startActivity(contacts);
}
};
// Getting reference to "Add Contact" button
Button btnAdd = (Button) findViewById(R.id.btn_add);
// Getting reference to "Contacts List" button
Button btnContacts = (Button) findViewById(R.id.btn_contacts);
// Setting click listener for the "Add Contact" button
btnAdd.setOnClickListener(addClickListener);
// Setting click listener for the "List Contacts" button
btnContacts.setOnClickListener(contactsClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}