Display phone contacts only in android - android

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;
}
}

Related

Add new contacts (36 items)

im trying to add new contacts to the phone but he does only the first 12 items.
i want to try all current 36 items and maybe more add to the phone contacts.
while ((line = bufferedReader.readLine()) != null) {
System.out.println("[[DEBUG]] [DW-UPDATE] LINE: " + line);
String[] split = line.split(";", -1);
split[2] = split[2].replace("/", "").replace("-", "");
if (!contactExists(mActivity, split[2])) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(split[0]))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, split[1])
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(split[0]))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, split[2])
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
try {
mActivity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
function contactExists:
public boolean contactExists(Activity _activity, String number) {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
}// contactExists
what i must do, to work this better?
Your problem is with your back references when adding the additional contact data. The back reference should refer to the position of your RawContacts.CONTENT_URI insert within your list of operations (ops), not the position of the contact within your raw data file. You can fix this by keeping track of the size of ops through each iteration:
if (!contactExists(mActivity, split[2])) {
int backRef = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(...)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(...)
.build()
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(...)
.build());
try {
mActivity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}

ContactsContract.RawContacts.VERSION is not changing

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");
}
}

adding contact automatically in phone book in android app

I need to add a contact automatically in phone book by my app....I found this link..
How to add new contacts in android
using this, I am able to add phone no.,name,email etc. But don't know how to add photo.
Firstly convert your image to bitmap and then use below code for adding photo to your contact.
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);
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());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(mBitmap!=null){ // If an image is selected successfully
mBitmap.compress(Bitmap.CompressFormat.PNG , 75, stream);
// Adding insert operation to operations list
// to insert Photo in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE,Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO,stream.toByteArray())
.build());
try {
stream.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
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();
}
}
};
For more details please refer below link
http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
Use following code this takes picture as photoByteArray for the method
private void addContact2() {
final String displayName = "XYZA";
final String mobileNumber = "666666";
final byte[] photoByteArray; // initalized elsewhere
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
//.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray)
.build());
Uri newContactUri = null;
ContentProviderResult[] res = null;
try {
final ContentResolver contentResolver = getContentResolver();
res = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
if (res != null && res.length > 0 && res[0] != null) {
newContactUri = res[0].uri;
Log.d(CallActivity.class.getName(), "URI added contact:"+ newContactUri);
Toast.makeText(this, "Successfully added " + displayName, Toast.LENGTH_LONG).show();
}
else Log.e(CallActivity.class.getName(), "Contact not added.");
} catch (NullPointerException | RemoteException | OperationApplicationException e) {
Log.e(CallActivity.class.getName(), e.getMessage(), e);
}
}

Android insert contact not showing name

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);
}
}

Android - How to get saved contact id

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.

Categories

Resources