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

Zoom Image - Android Tutorial

Here we are going to see how to zoom an image in Imageview Will see it through a sample 1. Create xml with an ImageView <? xml version="1.0" encoding="utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout       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"     tools:context=".MainActivity" >     < LinearLayout         android:layout_width="200dp"         android:layout_height="200dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"    ...

Multi language support

This post will help you yo learn how to make Multi language supported app in android. Why Multi language? In order to targeting global audience, it will be beneficial if you make your app localized. While localizing, you should think about text, audio, currency, numbers and graphics depending upon the region or country. But in this tutorial language only covered. Note: Whenever you are making any android application, Always declare text you want to use in your application in strings.xml only. <string name="hello">Hello World!</string> How String Localization Works? By default android considers English as primary language and loads the string resources from res >> values >> strings.xml . When you want to make Multilanguage supported app, you need to create a values folder by appending a Hyphen (-) and the ISO language code. For example for Hindi, values-hi named folder should be created and keep a strings.xml file in it wit...

Add custom font in Android using Calligraphy library

Are you fed up of Custom Views to set fonts? Or traversing the ViewTree to find TextViews? Sometime we want some other font for our Android application then you can add custom font in Android using Calligraphy library . Dependency Include the dependency Download (.aar) dependencies { compile ‘uk.co.chrisjenx:calligraphy:2.2.0’ } Add Fonts Add your custom fonts to assets/ . All font definitions are relative to this path. On Assets you should right-click New Directory, call it "fonts". In the finder put the .ttf  or .otf  font files in there. Create Class Create a class that extends Application and write this code public class App extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("your font path") .setFontAttrId(...