Sony Arouje

a programmer's log

Archive for July 2011

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 ,

%d bloggers like this: