This Android tutorial demonstrates how to get entire list of contacts available on the phone and display them using ListView and Cursor. This example also shows how to use SimpleCursorAdapter and how to map the column from a cursor to TextView.
Create the Android Project. Select File>New>Android Project in the Eclipse menu.
Create a class that extends the ListActivity class.
public class MainActivity extends ListActivity
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Next call the startManagingCursor(c);
This method helps the activity to take care of managing the Cursor's lifecycle based on the activity's lifecycle.
Now create mapping. This mapping helps to map the column from the content provider to the UI element. Later, pass this mapping as arguments to SimpleCursorAdapter constructor(in the next step).
// Column name representing the data to bind to UI
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
// View that should display column
int to[] = new int[] {android.R.id.text1};
Create and set the List Adapter by calling the constructor of SimpleCursorAdapter.
adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c ,columns ,to);
Next set the List Adapter by calling
setListAdapter(adapter);
Application needs the proper permission to read the data from Phone’s Contacts. Add following uses-permission in the AndroidManifest file:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Final code for MainActivity.java:
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get access and query the Contacts content provider
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
startManagingCursor(c);
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int to[] = new int[] {android.R.id.text1};
adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1 ,c , columns , to);
setListAdapter(adapter);
}
This example shows how you can display a list of items using ListActivity, Cursor and SimpleCursorAdapter.
Comments
Della (not verified)
Sun, 11/13/2011 - 00:22
Permalink
vizghcFriipHlRnxiMI
Super jazzed about gitetng that know-how.
Add new comment