Thursday, November 29, 2012

Query Contacts database, display in ListView.

The exercise "Query Contacts database" display result in TextView. It's modified to display in ListView.

Query Contacts database, display in ListView.


Modify layout to have a ListView.
<LinearLayout 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"
    tools:context=".MainActivity" 
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <ListView 
        android:id="@+id/conactlist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


package com.example.androidquerycontacts;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.content.CursorLoader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
 
 ListView listContacts;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  listContacts = (ListView)findViewById(R.id.conactlist);
  
  Uri queryUri = ContactsContract.Contacts.CONTENT_URI;

  String[] projection = new String[] {
    ContactsContract.Contacts._ID,
    ContactsContract.Contacts.DISPLAY_NAME};
  
  String selection = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
  
  CursorLoader cursorLoader = new CursorLoader(
            this, 
            queryUri, 
            projection, 
            selection, 
            null, 
            null);
  
  Cursor cursor = cursorLoader.loadInBackground();
  
  String[] from = {ContactsContract.Contacts.DISPLAY_NAME};
        int[] to = {android.R.id.text1};
        
        ListAdapter adapter = new SimpleCursorAdapter(
                this, 
                android.R.layout.simple_list_item_1, 
                cursor, 
                from, 
                to, 
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listContacts.setAdapter(adapter);
 }

}


download filesDownload the files.

Compare with:
- List images in MediaStore.Images.Media

Next:
- Handle Item Click on Query Contacts database ListView

No comments: