Sony Arouje

a programmer's log

List Contacts–My first Android app

with 21 comments

Last couple of days I am trying to get a hang on Android development. My first task is to setup the dev environment, I started with Intellij IDEA. Google considered Eclipse as their dev platform for Android. So I moved to Eclipse. Initially Android world is bit challenging as I am from .NET world. When I start working in Android, I feel comfortable. If you develop in Silverlight/WPF using MVVM then it’s not a big deal to create View and Activities in Android. I gone through one of the free ebook available for Android, now it’s time to practice what I learned.

Let’s go through my first app. Listing of contacts, obviously it’s a simple one. Below is my requirement.

  • List all the contact’s Display name
  • Click event on the list should also give ID of the contact not just name. So can able to load details of the contact by querying with ID.
  • Each contact should display with a graphics or an arrow or something. This will help me to learn binding view to ListView.

Output in emulator

image

 

Code walkthrough

I think it’s better start with the main activity and move forward. In this simple app I have only one activity called ContactListActivity.java. Oh forgot to tell you, activity is just like the viewmodels in MVVM (Silverlight/WPF). Activity handles all the UI related stuffs. Let’s see how the ContactListActivity looks

 

     1:  public class ContactListActivity extends ListActivity {

   2:      /** Called when the activity is first created. */
   3:      @Override
   4:      public void onCreate(Bundle savedInstanceState) {
   5:          super.onCreate(savedInstanceState);
   6:          ContactList contactList=this.getContacts();
   7:          ArrayAdapter<Contact> adapter=new ContactAdapter(this,contactList.getContacts());
   8:          setListAdapter(adapter);
   9:      }
  10:      
  11:      @Override
  12:      protected void onListItemClick(ListView l, View v, int position, long id)
  13:      {
  14:          super.onListItemClick(l, v, position, id);
  15:          Object o=this.getListAdapter().getItem(position);
  16:          Contact c=(Contact)o;
  17:          Toast.makeText(this, c.getDisplayName(), Toast.LENGTH_SHORT).show();
  18:      }
  19:      
  20:      private ContactList getContacts()
  21:      {
  22:          ContactList contactList=new ContactList();
  23:          Uri uri=ContactsContract.Contacts.CONTENT_URI;
  24:          ContentResolver cr=getContentResolver();
  25:          String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
  26:          Cursor cur=cr.query(uri, null, null, null, sortOrder);
  27:          if(cur.getCount()>0)
  28:          {
  29:              String id;
  30:              String name;
  31:              while(cur.moveToNext())
  32:              {
  33:                  Contact c =new Contact();
  34:                  id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
  35:                  name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
  36:                  c.setId(id);
  37:                  c.setDisplayName(name);
  38:                  contactList.addContact(c);
  39:              }
  40:          }
  41:          cur.close();
  42:          return contactList;
  43:      }
  44:  }
 

I don’t have any complex View for this activity so no xml file to link here. Normally an activity will have view that has textbox, button etc. It’s a good practice to define the layout (view) in xml file and Link to Activity. I will explain that later.

The above activity just list down all the contacts, so I inherited from ListActivity. As you can see I override onCreate method. This method will execute when activity get created. First thing I did in onCreate is get a list of contacts. Ignore where I created getContacts(), anyway it’s a test project so leave it.

In getContacts() you can see ContactList and Contact those two are domain class. Rest of the things are easy to understand if you have some knowledge in Android. If you are new to Android world better go through the book I mentioned at the begning of this post. getContacts() return ContactList object contains list of Contacts.

Next step is to bind the Contacts to ListView. Android uses Adapters to bind any kind of list to items control. Here in this case I am not just binding a string array, I am going to bind a view. So I created new Adapter extends from ArrayAdapter called ContactAdapter.

ContactAdapter.java

 

   1:  public class ContactAdapter extends ArrayAdapter<Contact> {
   2:   
   3:      private final List<Contact> _contacts;
   4:      private final Activity _context;
   5:      
   6:      public ContactAdapter(Activity context, List<Contact> contacts)
   7:      {
   8:          super(context,R.layout.contactlistitem,contacts);
   9:          this._contacts=contacts;
  10:          this._context=context;
  11:      }
  12:      static class ViewHolder {
  13:          protected TextView text;
  14:          private Contact  _contact;
  15:          protected void setContact(Contact contact)
  16:          {
  17:              text.setText(contact.getDisplayName());
  18:              _contact=contact;
  19:          }
  20:          protected Contact getContact() {return _contact;}
  21:      }
  22:      @Override
  23:      public Contact getItem(int position)
  24:      {
  25:          return _contacts.get(position);
  26:      }
  27:      @Override
  28:      public View getView(int position, View convertView, ViewGroup parent)
  29:      {
  30:          View view=null;
  31:          if(convertView==null)
  32:          {
  33:              LayoutInflater inflater=_context.getLayoutInflater();
  34:              view=inflater.inflate(R.layout.contactlistitem, null);
  35:              final ViewHolder viewHolder=new ViewHolder();
  36:              viewHolder.text=(TextView)view.findViewById(R.id.txtDisplayName);
  37:              viewHolder.setContact(_contacts.get(position));
  38:              view.setTag(viewHolder);
  39:          }
  40:          
  41:          return view;
  42:      }
  43:  }

 

As you can see in Line#8, I mentioned the View. So this adapter uses the specified view and bind it to ListView. You can find more about LayoutInflater here.

contactlistitem is an xml file and I defined in Layout folder.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="1">
    <TextView android:textAppearance="?android:attr/textAppearanceMedium" 
    android:text="TextView" 
    android:layout_height="wrap_content" 
    android:id="@+id/txtDisplayName" 
    android:layout_width="304dp"></TextView>
    
    <TextView android:textAppearance="?android:attr/textAppearanceLarge" 
    android:id="@+id/textView1" 
    android:text=">" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content"></TextView>
</LinearLayout>

R.* is an auto generated file contains the index to different stuffs in the project like Layout, controld identifier, etc.

Note: To create contacts in emulator you need to specify Virtual SD Card size say 200 Mib while creating the AVD through Android SDK and AVD Manager.

Download Source Code (ContactList.zip).

Written by Sony Arouje

July 29, 2011 at 4:02 pm

Posted in Android

Tagged with ,

21 Responses

Subscribe to comments with RSS.

  1. […] modified the ContactList test application to see how ORMLite works. Let’s go through in […]

  2. hey, i am getting a force close on click … and which string gives me the phone number of the clicked item …
    thanks for the amazing tutorial ….:)

    srikanth bhat

    August 8, 2011 at 4:50 pm

    • I am not sure why you are getting the error, you may need to debug and figure out what’s wrong. You can get the phone numbers of the contact as shown below

      //cr is an instance of contentresolver
      //Phone is an entity.
      public ArrayList getPhoneNumbers(String contactId) {
      ArrayList phones = new ArrayList();

      Cursor cur = this.cr.query(
      ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
      null,
      ContactsContract.CommonDataKinds.Phone.CONTACT_ID +” = ?”,
      new String[]{contactId}, null);
      while (cur.moveToNext()) {
      phones.add(new Phone(
      cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
      , cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))
      ));

      }
      cur.close();
      return(phones);

      Sony Arouje

      August 8, 2011 at 8:17 pm

  3. sir,plz tell me…this code have error in contact….i need it urgently m doing some app plz sir give me solution

    ciya

    November 10, 2011 at 1:21 am

    • Hi Ciya,
      I am not sure what kind of error your getting. The one I uploaded is working for me, I havent got any errors. Pls check whether you added any contacts to simulator, also verify whether you specified the virtual SD card size.

      Sony Arouje

      November 10, 2011 at 10:39 am

  4. ng

    ciya

    November 10, 2011 at 10:47 pm

  5. sir, m adding the contacts in emulator…i have got error in contact………….

    ciya

    November 10, 2011 at 10:50 pm

    • Ciya,
      Still u haven’t mentioned the details of the error. Please debug the code and find out what exactly the error is. Just saying ‘Error in contact’ will not help any one to figure out the issue.

      Sony Arouje

      November 11, 2011 at 10:08 am

  6. anyway thx…this essue has been solved………..sir, plz tell me the code of putting icon or image in a edit text and how to use hyperlink in android to open a new activity…………plz guide me

    ciya

    November 11, 2011 at 10:27 pm

    • Ciya.
      I have the same problem with “Contact”, can you please tell me how to solve this problem.

      megha

      September 16, 2014 at 4:17 pm

  7. very good sir

    Deewan singh

    July 20, 2012 at 2:43 pm

  8. Thanks for the code.thats great! but it gives an error when I scroll the listview in the phone(stopped unexpectedly.try again)pls help.thanks

    tharu

    August 18, 2012 at 11:29 am

    • Hi Tharu,
      I tested this code in a simulator, I am not doing much in Android world now. You can add a debugger or logger and check the error.

      Regards,
      Sony Arouje

      Sony Arouje

      August 19, 2012 at 1:08 pm

  9. Hello Sir ,
    I was running code given here and not able to understand from where the contacts will be fetched how is getcontcts() fetching the contscts

    Regards
    Neetu

    Anonymous

    April 6, 2013 at 11:31 am

    • Hi,
      I did this experiment very long ago and lost the touch with Android dev.

      Regards,
      Sony

      Sony Arouje

      April 9, 2013 at 12:28 pm

  10. Hi..

    Your app’s running perfectly. I’m a beginner in Android and I needed such an app to learn from and work on. Thanks!

    Regards
    Rusty

    Rusty

    April 9, 2013 at 6:47 pm

  11. thanks alot Sony
    your code is working perfectly
    could you please tell us how to display number along with name

    ssd

    May 9, 2013 at 8:46 am

    • Hi ssd,
      I am happy that you like my post and it helped you. Unfortunately I am not doing much in Android these days and I don’t think I will be able to answer your question. I am really sorry ssd.

      Regards,
      Sony

      Sony Arouje

      May 9, 2013 at 12:05 pm

  12. Hello, I have a problem. What is ContactList???

    Usman

    July 10, 2013 at 6:12 pm


Leave a Reply to ciya Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: