Skip to main content

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list.

After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the table, you will use query() method of ContentResolver to fetch the contact id. When you obtain the contact id, you can query the ContactsContract.CommonDataKinds.Phone table to retrieve the phone number for the selected contact.

Now to have an example application on getting phone number from contacts list.

STEP-1
Create a new Android project. 

STEP-2
activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context="com.example.mrbrown.contactlist.MainActivity">     <Button         android:id="@+id/idBtn"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Pick number from contacts list"         android:gravity="center_vertical"         android:background="">     </Button>     <TextView         android:id="@+id/idTxtName"         android:layout_below="@+id/idBtn"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="10dp"         android:textStyle="bold"         android:textSize="25dp"         android:textColor="@color/colorPrimary"/>     <TextView         android:id="@+id/idTxtNumber"         android:layout_below="@+id/idTxtName"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="10dp"         android:textStyle="bold"         android:textSize="25dp"         android:textColor="@color/colorAccent"/> </RelativeLayout>


STEP-3
MainActivity.java

public class MainActivity extends Activity {

    public Button btnSelect;
    public TextView txtName;
    public TextView txtNumber;
    private final int REQUEST_CODE=99;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnSelect=(Button)findViewById(R.id.idBtn);
        txtName=(TextView)findViewById(R.id.idTxtName);
        txtNumber=(TextView)findViewById(R.id.idTxtNumber);

        btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, 
ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
    }

    @Override public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);
        switch (reqCode) {
            case (REQUEST_CODE):
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor c = getContentResolver().query
(contactData, null, null, null, null);
                    if (c.moveToFirst()) {
                        String contactId = c.getString(c.getColumnIndex
(ContactsContract.Contacts._ID));
                        String hasNumber = c.getString(c.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        String num = "";
                        String name = "";
                        if (Integer.valueOf(hasNumber) == 1) {
                            Cursor numbers = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                            while (numbers.moveToNext()) {
        num = numbers.getString(numbers.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Toast.makeText(MainActivity.this, "Number="+num, Toast.LENGTH_LONG).show();
name = numbers.getString(numbers.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                                txtName.setText(""+name);
                                txtNumber.setText(""+num);
                            }
                        }
                    }
                    break;
                }
        }
    }
}

STEP-4
Add permission to Manifest file
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Output Screenshots
________________________________________________
Source code for this SampleProject.rar
Happy Coding...

Comments

Post a Comment

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...