In this tutorial, I will explain to you how we can add a contact number programmatically through our Android application. With the help of this post, you can easily add a new contact and get a list from the contact database and also remove the contact.
Step 1. Create a new Android project using Android Studio.
Step 2. Once your project you need to edit AndroidManifest.xml
file and add READ_CONTACTS / WRITE_CONTACTS
permission in your manifest file.
<uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.READ_CONTACTS" />
Step 3. After adding permission in the manifest file we also need to request for permission programmatically for API 23 or greater in our MainActivity
class.
private void contactPermission() { if (android.os.Build.VERSION.SDK_INT >= 23) { // only for gingerbread and newer versions String permission = Manifest.permission.WRITE_CONTACTS; if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS}, Permission_Request); } else { permissionOperation = true; } } else { permissionOperation = true; } }
And when the user allows you to write contact you can handle that inside onRequestPermissionsResult
, If the user denies you to write contact you can request again as shown in the below code.
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case Permission_Request: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Add your function here which open camera } else { boolean somePermissionsForeverDenied = false; for(String permission: permissions){ if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){ //denied Log.e("denied", permission); }else{ if(ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED){ //allowed Log.e("allowed", permission); } else{ //set to never ask again Log.e("set to never ask again", permission); somePermissionsForeverDenied = true; } } } if(somePermissionsForeverDenied){ final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("Permissions Required") .setMessage("You have forcefully denied some of the required permissions " + "for this action. Please open settings, go to permissions and allow them.") .setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getPackageName(), null)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setCancelable(false) .create() .show(); } Toast.makeText(getApplication(), "Permission required", Toast.LENGTH_LONG).show(); } return; } } }
Step 4. Now open activity_main.xml file and create fields from where we can add a contact. I
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <EditText android:id="@+id/given_name" android:hint="Name" android:layout_width="match_parent" android:layout_height="wrap_content"></EditText> <EditText android:id="@+id/family_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Family Name"></EditText> <EditText android:id="@+id/mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Mobile"></EditText> <EditText android:id="@+id/home" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Home"></EditText> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email"></EditText> <Button android:id="@+id/save" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save"></Button> <Button android:id="@+id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="List Contacts"></Button> </LinearLayout>
Step 5. Once our screen is ready we can handle data entry on that screen and save into contact using ContentProvider. When the user clicks on the save button we can call addContact()
function and save data in the contacts database.
private void addContact(String given_name, String name, String mobile, String home, String email) { ArrayList<ContentProviderOperation> contact = new ArrayList<ContentProviderOperation>(); contact.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) .build()); // first and last names contact.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, 0) .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, given_name) .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, name) .build()); // Contact No Mobile contact.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, 0) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobile) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) .build()); // Contact Home contact.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, 0) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, home) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME) .build()); // Email ` contact.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, 0) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Email.DATA, email) .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK) .build()); try { ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, contact); } catch (Exception e) { e.printStackTrace(); } }
Get a list of contact in Android App
Step 6. Now If you want to show the list of contacts you can use the below method.
private ArrayList getAllContacts() { ArrayList<String> nameList = new ArrayList<>(); ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if ((cur != null ? cur.getCount() : 0) > 0) { while (cur != null && cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)); ContactModel contactModel = new ContactModel(); contactModel.setName(name); contactModel.setId(id); String phoneNo = ""; nameList.add(name); if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null); while (pCur.moveToNext()) { phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Log.e("phone", phoneNo+" phone"); if(phoneNo.length() > 0) contactModel.setPhone(phoneNo); } pCur.close(); } contactModelArrayList.add(contactModel); } contactListAdapter.notifyDataSetChanged(); } if (cur != null) { cur.close(); } return nameList; }
Remove contact programmatically
Step 7. If you want to remove contacts programmatically you can use this code.
public void deleteContact(String id) { long rawContactId = Long.parseLong(id); ContentResolver contentResolver = getContentResolver(); Uri dataContentUri = ContactsContract.Data.CONTENT_URI; // Create data table where clause. StringBuffer dataWhereClauseBuf = new StringBuffer(); dataWhereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID); dataWhereClauseBuf.append(" = "); dataWhereClauseBuf.append(rawContactId); contentResolver.delete(dataContentUri, dataWhereClauseBuf.toString(), null); Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI; // Create raw_contacts table where clause. StringBuffer rawContactWhereClause = new StringBuffer(); rawContactWhereClause.append(ContactsContract.RawContacts._ID); rawContactWhereClause.append(" = "); rawContactWhereClause.append(rawContactId); // Delete raw_contacts table related data. contentResolver.delete(rawContactUri, rawContactWhereClause.toString(), null); Uri contactUri = ContactsContract.Contacts.CONTENT_URI; // Create contacts table where clause. StringBuffer contactWhereClause = new StringBuffer(); contactWhereClause.append(ContactsContract.Contacts._ID); contactWhereClause.append(" = "); contactWhereClause.append(rawContactId); // Delete raw_contacts table related data. contentResolver.delete(contactUri, contactWhereClause.toString(), null); }
That’s it. You can download the complete code from the below link. Hope this post helps you to save and remove a contact from your application.