how to Insert New Contact in Android Code Example easy way

how to Insert New Contact in Android Code Example – allntech

Insert new contact in Android is very easy. Here we will learn how to add a new mobile number into Android Contacts list programmatically. We will use inbuilt Android classes (ContactsContract, ContentProviderOperation) to feature new contacts in Android Contacts List. and Below is the code snippet with example and detailed description.

Step 1:
Add below packages into your java class from where you want to insert new contact into your Contacts List. You can add below packages into your Activity’s class to test the functionality easily. Then you can move the code into any java class.

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;

this is the article of how to Insert New Contact in Android Code Example
Step 2:
if you want to Insert New Contact in Android Code Example Now add below function WritePhoneContact() in your java class where you have already added packages (mentioned in Step 1 above ).

Once you added below function into your java class then you have to just call that function to add a new contact into the Android contacts list. To test the functionality, you can add below function (code snippet) into your Activity’s class.

this is the article of how to Insert New Contact in Android Code Example easy way
Note: You can find detailed inline code description inside the code.

public void WritePhoneContact(String displayName, String number,Context cntx /*App or Activity Ctx*/)
{
	Context contetx 	= cntx; //Application's context or Activity's context
	String strDisplayName 	=  displayName; // Name of the Person to add
	String strNumber 	=  number; //number of the person to add with the Contact
		
	ArrayList<ContentProviderOperation> cntProOper = new ArrayList<ContentProviderOperation>();
        int contactIndex = cntProOper.size();//ContactSize

        //Newly Inserted contact
        // A raw contact will be inserted ContactsContract.RawContacts table in contacts database.
        cntProOper.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)//Step1
                .withValue(RawContacts.ACCOUNT_TYPE, null)
                .withValue(RawContacts.ACCOUNT_NAME, null).build());

        //Display name will be inserted in ContactsContract.Data table
        cntProOper.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)//Step2
                .withValueBackReference(Data.RAW_CONTACT_ID,contactIndex)
                .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                .withValue(StructuredName.DISPLAY_NAME, strDisplayName) // Name of the contact
                .build());
        //Mobile number will be inserted in ContactsContract.Data table
        cntProOper.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)//Step 3
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,contactIndex)
                .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                .withValue(Phone.NUMBER, strNumber) // Number to be added
                .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); //Type like HOME, MOBILE etc
        try
        {
                // We will do batch operation to insert all above data 
        	//Contains the output of the app of a ContentProviderOperation. 
        	//It is sure to have exactly one of uri or count set
            ContentProviderResult[] contentProresult = null;
            contentProresult = contetx.getContentResolver().applyBatch(ContactsContract.AUTHORITY, cntProOper); //apply above data insertion into contacts list 
        }
        catch (RemoteException exp)
        { 
            //logs;
        }
        catch (OperationApplicationException exp) 
        {
            //logs
        }       
}


Code Description:

WritePhoneContact(String displayName, String number,Context cntx /*App or Activity Ctx*/)


Similarity In the above function, You can pass arguments as below.
String displayName: Contact’s name (Example John), which need to be add in Android contact list.
String number: Mobile number of the person (Example: 9999999999) which need to be add with the contact (John in our example).


Context cntx: This is nothing but your Activity’s context’s or you can provide your application’s context. Just for the testing purpose, you can call above function from your Activity’s onCreate() function like in Step 3 below.

this is the article of how to Insert New Contact in Android Code Example easy way


Step 3:
if you want Insert New Contact in Android Code Example therefore Call the above mentioned function WritePhoneContact() as below.

@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contacts_backup_restore);
                // Pass below variable <em>cntx</em> into the WritePhoneContact() function as third variable.
		<em>Context cntx</em> = getApplicationContext(); // get application context
                //Now call below function to do the real task for you.
                WritePhoneContact("John", "9999999999",cntx);

         }


That’s it. I hope this small tutorial on how to add new contacts into Android Contacts list will help it it’s best. If you are facing any issue, then please feel free to contact us, we will try to revert you asap.


Note: If you want to invoke the native Contacts Activity for inserting a new contact, then you may follow below code.

//Add below packages in your java class
import android.net.Uri;
import android.content.Intent;
import android.provider.ContactsContract;
//Then add below code for inserting a new contact using intent
		//create a new intent for inserting contact
		Intent contactIntent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT,ContactsContract.Contacts.CONTENT_URI);
		contactIntent.setData(Uri.parse("tel:+919999999999"));//Add the mobile number here
		contactIntent.putExtra(ContactsContract.Intents.Insert.PHONE, "John"); //ADD contact name here
        //Below Start activity function will display the Add contacts native screen along with your input data
        startActivity(contactIntent);


You might like to read my Android tutorial “How to read multiple phone numbers in Android Contacts List Programmatically”.

this is the article of how to Insert New Contact in Android Code Example easy way

Read Multiple Phone Numbers From Android Contacts List Programmatically

It is very easy to retrieve phone numbers in Android. This is how you can read multiple phone numbers from Android Contacts List programmatically. If a contact has multiple phone numbers, then you’ll retrieve all phone numbers and other details using Android’s inbuilt classes (Cursor and ContactsContract ) in Android.

how to Insert New Contact in Android Code Example
how to Insert New Contact in Android Code Example


Below is the code snippet for reading all contact details from your Android device. Above all, most importantly, certainly


Step 1:

Insert New Contact in Android Code Example so Add below packages in your Activity class or from the class where you want to read all contacts.

allntech.com

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;


Step 2:
Add below permission in your application’s Manifest file (AndroidManifest.xml).

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>


Step 3:
Add the below function (Copy and paste) below code snippet into your in your Activity class or from the class where you want to read all contacts. You can read inline comments inside the code. I have added details code description inside the code snippet below.

public void ReadPhoneContacts(Context cntx) //This Context parameter is nothing but your Activity class's Context
	{
		Cursor cursor = cntx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list 
		if (contactsCount > 0)
		{
		    while(cursor.moveToNext())
		    {
		        String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
		        String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		        if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) 
		        {
		        	//the below cursor will give you details for multiple contacts
		        	Cursor pCursor = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
		            		 										ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
		            		 										new String[]{id}, null);
		            // continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list  
		        	while (pCursor.moveToNext())
		             {
		                  int phoneType 		= pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
		                  //String isStarred 		= pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
		                  String phoneNo 	= pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
		                  //you will get all phone numbers according to it's type as below switch case.
		                  //Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
		                  switch (phoneType)
		                  {
		                        case Phone.TYPE_MOBILE:
		                            Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
		                            break;
		                        case Phone.TYPE_HOME:
		                            Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
		                            break;
		                        case Phone.TYPE_WORK:
		                            Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
		                            break;
		                        case Phone.TYPE_WORK_MOBILE:
		                            Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
		                            break;            
		                        case Phone.TYPE_OTHER:
		                            Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
		                            break;
		                        default:
		                            break;
		                  }
	              }
		          pCursor.close();
		        }
		    }
		    cursor.close();
		}
	}


Case 3: You just need to call above function from where you want to read phone numbers from the contacts list.

//Call this function from your Activity Class 
//Below this pointer parameter is your Activity class's this pointer
//If you want to call below function from other classes or from a service,
//then get the Context of your application or Activity and pass it to function 
//ReadPhoneContacts(cntx);

PhoneContacts phoneContacts = new PhoneContacts(service);
phoneContacts.ReadPhoneContacts(cntx);

this is the article of how to Insert New Contact in Android Code Example easy way


Code Description:

• The parameter ‘Context cntx’ in the function ReadPhoneContacts(Context cntx) is nothing but the this pointer of your Acticity class or application Context.
• There are 2 while loops in above code, First while loop is for the Cursor (cursor variable in the above code), which moves exactly once for each contact in the Android contacts list. Second while loop moves exactly once for each phone number associated with the contact name (contactName variable in the above code) using the second cursor (pCursor variable in the above code).


• You can find the Contact Name in the variable(contactName variable in the above code). Then you will go into all phone numbers, which are associated with the Contact Name (contactName variable in the above code).


• In the Switch Case above (switch (phoneType) in the above code snippet), Each case having phone type like (TYPE_MOBILE, TYPE_HOME ect) in the switch case. In the switch case, you can find the variable phoneNo , which will provide the phone number for each phone type. Logs.e() function will print the numbers in DDMS if your phone/emulator is connected to your Eclipse editor. Else you can use the variable phoneNo as per your requirement.


I hope this code snippet will help you at it’s best. If you have any concern or queries, then let me know. I will try to resolve your queries.

this is the article of how to Insert New Contact in Android Code Example easy way


You might like to read about the complete tutorial for how to retrieve contacts and then display in a ListView in Android.


Sample Code for retrieve Contacts List and display in a ListView in Android
Recommended Post for You – Add New Contact in Android Code Example.

Follow US FACEBOOK INSTAGRAM

Steps to Download Android Apps from Google Play Store

Fully Automatic Washing Machine makes washing easy

Communication Between Service and Activity in Android Example

Mozilla Firefox OS – New Competitor in Smartphone Market

Insert New Contact in Android Code Example

The Best Ways to Transfer Photos from Your iPhone to Your Laptop

Top five payment gateway list that you must know cheap

Leave a Comment