Android Programming: Reading Phone Contacts

In this Article, we will write code to read User’s name and phone contact number.

Below are the main activities that we need to incorporate in the code:

  1. Assigning Read access permission to read user’s contacts. Add the below line to AndroidManifest.xml file:


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


Or add the permissions from the AndroidMenifest.xml UI as shown below:




2.  Below is the code for activity_main.xml where we have defined TextView where we will display the User’s name and contact number.



<LinearLayout xmlns:android=""
    tools:context=".MainActivity" >

        android:text="" />




3) Below is the Java code from file: In this file, the function that is fetching the User’s contact details is GetMyPhoneContacts(). In this function, we have used a column list and a query which will return User’s contact details in the cursor.

Below is the information about the query method that we have used:

Cursor android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Query the given URI, returning a Cursor over the result set.



The URI, using the content:// scheme, for the content to retrieve.


A list of which columns to return. Passing null will return all columns, which is inefficient.


A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.


You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.


How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. We have used Ascending order in this example.

Once the above query will return data in cursor, we will fetch the individual row in do while loop on the cursor. In the loop we are fetching the name and contact number of the user and appending it to the TextView.




package com.example.testapp;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.content.res.Configuration;
import android.database.Cursor;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {



    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub

	public void GetMyPhoneContacts()
		String[] mProjection=new String[]

		String strName = null;
		String strPhoneNumber = null;
		TextView txtvw = (TextView) findViewById(;

		Cursor curPhoneContacts = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, mProjection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " Asc");



			strName = curPhoneContacts.getString(curPhoneContacts.getColumnIndex(Contacts.DISPLAY_NAME));
			strPhoneNumber = curPhoneContacts.getString(curPhoneContacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			txtvw.append("\nName-->" + strName + "\n");
			txtvw.append("Phone Number-->" + strPhoneNumber + "\n\n\n");

		}while (curPhoneContacts.moveToNext());











Android Programming : Screen orientation–Portrait / Landscape

Every mobile screen have two orientations, one is Portrait and the other is Landscape.

Whenever you will run your application on the mobile device, you can see it in either orientations. You may want to have different screen layout in the different screen orientations.

Portrait Layout:




Landscape Layout:




Now to make your App screen to work in both orientations as expected, please follow the below steps:

  1. As shown in the below screenshot, under “res” folder, create a new folder with the name “layout-land”, -land appended for landscape orientation.
  2. For landscape orientation, create layout xml under “layout-land” folder with the same name as of the layout xml under “layout” folder. Note that name of the xml file in layout and layout-land folder should be same.



Having done the above steps, now when you will run your Android App in the Simulator or the actual device, when you will keep the screen in the portrait orientation, layout xml under layout folder will be picked up and when you will put the screen in the landscape mode, layout xml under layout-land folder will be picked up.

Note: To change the orientation of the screen in simulator, press Ctrl + F11.

Example from my latest App: Below are the screenshots from both the orientations. Please note the placement of the UI components in both the screens. I have created separate XML for the modes.

In Portrait mode: 


In Landscape mode:


Android Application Deployment without Play Store

Guys, Created your application! Huh….

Planning to get this application installed on actual device of yours or your friend….and you don’t want to install it through Android Market! (Play Store), you can do it by following below steps:


On the actual Android device, go to Settings > Applications


Check the checkbox for “Unknown sources” to allow installation of the non-Market applications. It is shown below:

Note: Once the installation is done, I would recommend to un-check it.



Copy *.apk file (for BMICalculator example, copy BMICalculator.apk) from the location (workspace\[ProjectName]\bin) to the target Android device. In my case it is “C:\Users\demo\workspace\BMICalculator\bin”.

For distribution purpose, you can email/copy *.apk file to the target audience. You can upload this apk file to some ftp location or some site, and then you can send that link to the target audience.

Once the *.apk file is copied to the target device, double click it. It will then get installed on the device. You can now go to the applications screen and see the application icon as shown below:




Double click the icon and this will launch your application.

Android Application–Creating the first Application

Guys, lets start Android magic!

Go to the eclipse location (C:\Development\adt-bundle-windows-x86\eclipse) and double click on eclipse.exe.

It will launch the eclipse development platform.


Go to File > New > Android Application Project as shown below:




Below screen will be popped up: Enter the application name. Please note that the package name should be unique. Best practice is to have its format like “com.[site name].[app name].

Select the Minimum required SDK, Target SDK and Compile with options. This is based on your requirement. I have android 2.3.3, so I have selected it as Target SDK.

Based on the Target SDK, select Theme. Click Next.




Below screen will appear. Keep the default values and select Next.




Below screen will appear:

For this first application, Keep the default values and select Next.

You can also select the Icon for your application.




Below screen will appear:

For this first application, Select BlankActivity and select Next.

This selection depends on the Target SDK you selected before. For few SDK, some Activity will not be available.

This will basically create your application UI.




Below screen will appear:

Change the Activity name as BMIMainActivity and select Finish. This will create your first application. Coooool………..




This will be the first look and feel of the application you just have created.

By default, it will have TextView with the text set to “Hello World”.




Below screen shows the XML part of the above Layout.




Now guys, lets see the project structure. On the left bottom corner, click on the plus icon. Below screen will appear. Select the Project Explorer.




Below is the Android project structure.

Lets now understand its structure….

First folder is called “src”. It holds all the Java class files. Folder “res”, hold all the resources like the image files, sound files, Layout etc.

From below screen, you must have noticed many folders with the name “drawable-hdpi” , “drawable-ldpi”, “drawable-mdpi” etc. Here hd means high definition, ld means low definition and md means medium definition.

Folder layout have all the UI files in XML format.

Folder values, has string.xml file where you need to define any of your global variables that you will use in the layout xml files. This will reduce the hardcoding in the XML file as all the values will be defined in the single place.

AndroidManifest.xml file is the file where information about the Android application is stored.

Below series of screenshot will show the above files.



Below screen is showing the main java file which has two methods by default. Main method is “onCreate” method. This will be the starting point of the application.




Below screen is showing the string.xml file where we can define any number of the variable that will ne used in the layout xml file. Below screen is also showing the “Hello World” value that is getting displayed on the main UI. You just need to change it here and not in the layout XML file. This will make the changes/maintenance easy for the application developers.




Below screen is showing the AndroidManifest.xml file.

This file has all information required to run the Android application. I have highlighted few important lines in the below screen. First highlighted line is the complete name of the class. Second shows that it is the main class and third line tell Android OS that this is the launcher class and it will be launched whenever Android application will be executed.



This is all about the program structure.

Now lets see how to run this application.

For this Article, I will run the application on the Android Virtual device. Its just a simulator.

To run it on the simulator, we need follow few steps. Here are those steps.

Go to Windows > Android Virtual Device Manager as shown below:



Below screen will appear. Click on “New”.




Below screen will appear:

Enter AVD Name. Select any device. Make sure to select the Target Android version for which you have created the application. Keep others as default and click Ok.




It will create Android Virtual device as shown below:

Click Start to see if it is working properly.




Below screen will appear:

Change the Screen Size (in) to 6 and then click on “Launch”.




This will launch the Android Virtual device as shown below:

This shows that you have correctly setup the virtual device. You are doing great!




Now from the eclipse, go to Run > Run Configuration to configure how you are going to run your Android Application.




Below screen will appear. Double click on Android Application node on the tree at left hand side. It will create new configuration. Click on the Browse button and select your application as shown below:




Now select second tab “Target” and select the virtual device that you have created above. Finally click on Run. From next time, you just need to press Ctrl + F11 to the run the application.

Your can also select the option which will ask you to select the device before running the application.




Below is the output of your First Application on the Android Virtual device.




Happy Android Programming.