Initial integration with Directory API

Change-Id: I121e1e3b5a365204ffdd736b00133fd97529719e
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 5274b99..76512fe 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -264,7 +264,7 @@
         <!-- The contacts search/filter UI -->
         <activity android:name="ContactsSearchActivity"
             android:theme="@style/ContactsSearchTheme"
-            android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
+            android:windowSoftInputMode="stateAlwaysVisible"
         >
             <intent-filter>
                 <action android:name="com.android.contacts.action.FILTER_CONTACTS" />
diff --git a/res/drawable/directory_bg.9.png b/res/drawable/directory_bg.9.png
new file mode 100644
index 0000000..80578cd
--- /dev/null
+++ b/res/drawable/directory_bg.9.png
Binary files differ
diff --git a/res/layout-finger/contacts_search_content.xml b/res/layout-finger/contacts_search_content.xml
index 480a8aa..d36ad00 100644
--- a/res/layout-finger/contacts_search_content.xml
+++ b/res/layout-finger/contacts_search_content.xml
@@ -40,6 +40,7 @@
         android:layout_width="match_parent"
         android:layout_height="0dip"
         android:layout_weight="1"
+        android:visibility="gone"
     />
     <ViewStub android:id="@+id/footer_stub"
         android:layout="@layout/footer_panel"
diff --git a/res/layout-finger/directory_header.xml b/res/layout-finger/directory_header.xml
new file mode 100644
index 0000000..53207e0
--- /dev/null
+++ b/res/layout-finger/directory_header.xml
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<!-- Layout used for list section separators. -->
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="48dip"
+    android:background="@drawable/directory_bg"
+    >
+    <TextView
+        android:id="@+id/count"
+        android:layout_height="wrap_content"
+        android:layout_width="wrap_content"
+        android:layout_centerVertical="true"
+        android:layout_alignParentRight="true"
+        android:layout_marginRight="8dip"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+        android:textColor="?android:attr/textColorSecondary"
+    />
+    <TextView
+        android:id="@+id/display_name"
+        android:layout_height="wrap_content"
+        android:layout_width="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentBottom="true"
+        android:layout_alignWithParentIfMissing="true"
+        android:layout_marginLeft="6dip"
+        android:textAppearance="?android:attr/textAppearanceSmall"
+        android:singleLine="true"
+    />
+    <TextView
+        android:id="@+id/directory_type"
+        android:layout_height="wrap_content"
+        android:layout_width="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_centerVertical="true"
+        android:layout_marginLeft="6dip"
+        android:layout_marginBottom="-4dip"
+        android:layout_above="@id/display_name"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+        android:singleLine="true"
+    />
+
+</RelativeLayout>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 634e65d..29a39df 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -331,17 +331,17 @@
 
     <!-- Displayed at the top of the contacts showing the total number of contacts found when "Only contacts with phones" not selected -->
     <plurals name="listFoundAllContacts">
-        <item quantity="one">Found 1 contact</item>
-        <item quantity="other">Found <xliff:g id="count">%d</xliff:g> contacts</item>
+        <item quantity="one">1 found</item>
+        <item quantity="other"><xliff:g id="count">%d</xliff:g> found</item>
     </plurals>
 
     <!-- Displayed at the top of the contacts showing the zero total number of contacts found when "Only contacts with phones" not selected -->
-    <string name="listFoundAllContactsZero">Contact not found</string>
+    <string name="listFoundAllContactsZero">Not found</string>
 
     <!-- Displayed at the top of the contacts showing the total number of contacts found when typing search query -->
     <plurals name="searchFoundContacts">
-        <item quantity="one">1 contact</item>
-        <item quantity="other"><xliff:g id="count">%d</xliff:g> contacts</item>
+        <item quantity="one">1 found</item>
+        <item quantity="other"><xliff:g id="count">%d</xliff:g> found</item>
     </plurals>
 
     <!-- The description text for the contacts tab. Space is limited for this string, so the shorter the better -->
diff --git a/src/com/android/contacts/list/ContactEntryListAdapter.java b/src/com/android/contacts/list/ContactEntryListAdapter.java
index a0dd32b..dac1d62 100644
--- a/src/com/android/contacts/list/ContactEntryListAdapter.java
+++ b/src/com/android/contacts/list/ContactEntryListAdapter.java
@@ -26,10 +26,14 @@
 import android.database.Cursor;
 import android.os.Bundle;
 import android.provider.ContactsContract.ContactCounts;
+import android.provider.ContactsContract.Directory;
 import android.text.TextUtils;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
+import android.widget.TextView;
+
+import java.util.HashMap;
 
 /**
  * Common base class for various contact-related lists, e.g. contact list, phone number list
@@ -37,6 +41,8 @@
  */
 public abstract class ContactEntryListAdapter extends IndexerListAdapter {
 
+    private static final String TAG = "ContactEntryListAdapter";
+
     /**
      * The animation is used here to allocate animated name text views.
      */
@@ -55,6 +61,8 @@
     private boolean mLoading = true;
     private boolean mEmptyListEnabled = true;
 
+    private HashMap<Integer, DirectoryPartition> mPartitions;
+
     public ContactEntryListAdapter(Context context) {
         super(context, R.layout.list_section, R.id.header_text);
         addPartitions();
@@ -68,8 +76,17 @@
         addPartition(false, false);
     }
 
+    public void addDirectoryPartition(DirectoryPartition partition) {
+        if (mPartitions == null) {
+            mPartitions = new HashMap<Integer, DirectoryPartition>();
+        }
+        int partitionIndex = getPartitionCount();
+        mPartitions.put(partitionIndex, partition);
+        addPartition(partition.showIfEmpty, partition.directoryType != null);
+    }
+
     public abstract String getContactDisplayName(int position);
-    public abstract void configureLoader(CursorLoader loader);
+    public abstract void configureLoader(CursorLoader loader, long directoryId);
 
     public boolean isSearchMode() {
         return mSearchMode;
@@ -77,6 +94,7 @@
 
     public void setSearchMode(boolean flag) {
         mSearchMode = flag;
+        setPinnedPartitionHeadersEnabled(flag);
     }
 
     public boolean isSearchResultsMode() {
@@ -206,36 +224,39 @@
     }
 
     @Override
-    public int getCount() {
-        int count = super.getCount();
-
-        if (mSearchMode) {
-            // Last element in the list is "Search all contacts"
-            count++;
-        }
-
-        return count;
-    }
-
-    public boolean isSearchAllContactsItemPosition(int position) {
-        return isSearchMode() && position == getCount() - 1;
+    protected View newHeaderView(Context context, int partition, Cursor cursor,
+            ViewGroup parent) {
+        LayoutInflater inflater = LayoutInflater.from(context);
+        return inflater.inflate(R.layout.directory_header, parent, false);
     }
 
     @Override
-    public int getItemViewType(int position) {
-        if (isSearchAllContactsItemPosition(position)) {
-            return IGNORE_ITEM_VIEW_TYPE;
+    protected void bindHeaderView(View view, int partition, Cursor cursor) {
+        DirectoryPartition directoryPartition = mPartitions.get(partition);
+        TextView directoryTypeTextView = (TextView)view.findViewById(R.id.directory_type);
+        directoryTypeTextView.setText(directoryPartition.directoryType);
+        TextView displayNameTextView = (TextView)view.findViewById(R.id.display_name);
+        if (!TextUtils.isEmpty(directoryPartition.displayName)) {
+            displayNameTextView.setText(directoryPartition.displayName);
+            displayNameTextView.setVisibility(View.VISIBLE);
+        } else {
+            displayNameTextView.setVisibility(View.GONE);
         }
 
-        return super.getItemViewType(position);
+        int count = cursor == null ? 0 : cursor.getCount();
+        TextView countText = (TextView)view.findViewById(R.id.count);
+        countText.setText(getQuantityText(count, R.string.listFoundAllContactsZero,
+                  R.plurals.searchFoundContacts));
     }
 
-    @Override
-    public View getView(int position, View convertView, ViewGroup parent) {
-        if (isSearchAllContactsItemPosition(position)) {
-            return LayoutInflater.from(getContext()).inflate(
-                    R.layout.contacts_list_search_all_item, parent, false);
+    // TODO: fix PluralRules to handle zero correctly and use Resources.getQuantityText directly
+    public String getQuantityText(int count, int zeroResourceId, int pluralResourceId) {
+        if (count == 0) {
+            return getContext().getString(zeroResourceId);
+        } else {
+            String format = getContext().getResources()
+                    .getQuantityText(pluralResourceId, count).toString();
+            return String.format(format, count);
         }
-        return super.getView(position, convertView, parent);
     }
 }
diff --git a/src/com/android/contacts/list/ContactEntryListFragment.java b/src/com/android/contacts/list/ContactEntryListFragment.java
index f9f7b77..08ccabd 100644
--- a/src/com/android/contacts/list/ContactEntryListFragment.java
+++ b/src/com/android/contacts/list/ContactEntryListFragment.java
@@ -22,6 +22,7 @@
 import com.android.contacts.R;
 import com.android.contacts.ui.ContactsPreferences;
 import com.android.contacts.widget.ContextMenuAdapter;
+import com.google.android.collect.Lists;
 
 import android.accounts.Account;
 import android.accounts.AccountManager;
@@ -34,21 +35,22 @@
 import android.content.IContentService;
 import android.content.Intent;
 import android.content.Loader;
+import android.content.pm.PackageManager;
 import android.database.ContentObserver;
 import android.database.Cursor;
+import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Parcelable;
 import android.os.RemoteException;
 import android.provider.ContactsContract;
 import android.provider.Settings;
+import android.provider.ContactsContract.Directory;
 import android.provider.ContactsContract.ProviderStatus;
 import android.telephony.TelephonyManager;
-import android.text.Editable;
 import android.text.Html;
 import android.text.TextUtils;
 import android.util.Log;
-import android.view.KeyEvent;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
@@ -56,7 +58,6 @@
 import android.view.View.OnClickListener;
 import android.view.View.OnFocusChangeListener;
 import android.view.View.OnTouchListener;
-import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.AbsListView;
 import android.widget.AdapterView;
@@ -66,6 +67,8 @@
 import android.widget.AbsListView.OnScrollListener;
 import android.widget.AdapterView.OnItemClickListener;
 
+import java.util.ArrayList;
+
 /**
  * Common base class for various contact-related list fragments.
  */
@@ -73,17 +76,23 @@
         extends LoaderManagingFragment<Cursor>
         implements OnItemClickListener, OnScrollListener, OnFocusChangeListener, OnTouchListener {
 
+
     private static final String TAG = "ContactEntryListFragment";
 
     private static final String LIST_STATE_KEY = "liststate";
 
+    private static final String DIRECTORY_ID_ARG_KEY = "directoryId";
+
+    private static final int DIRECTORY_LOADER_ID = -1;
+
+    private ArrayList<DirectoryPartition> mDirectoryPartitions = Lists.newArrayList();
+
     private boolean mSectionHeaderDisplayEnabled;
     private boolean mPhotoLoaderEnabled;
     private boolean mSearchMode;
     private boolean mSearchResultsMode;
     private String mQueryString;
 
-    private CursorLoader mLoader;
     private T mAdapter;
     private View mView;
     private ListView mListView;
@@ -105,6 +114,23 @@
 
     private int mProviderStatus = ProviderStatus.STATUS_NORMAL;
 
+    private static final class DirectoryQuery {
+        public static final Uri URI = Directory.CONTENT_URI;
+        public static final String ORDER_BY = Directory._ID;
+
+        public static final String[] PROJECTION = {
+            Directory._ID,
+            Directory.PACKAGE_NAME,
+            Directory.TYPE_RESOURCE_ID,
+            Directory.DISPLAY_NAME,
+        };
+
+        public static final int ID = 0;
+        public static final int PACKAGE_NAME = 1;
+        public static final int TYPE_RESOURCE_ID = 2;
+        public static final int DISPLAY_NAME = 3;
+    }
+
     protected abstract View inflateView(LayoutInflater inflater, ViewGroup container);
     protected abstract T createListAdapter();
 
@@ -115,10 +141,6 @@
      */
     protected abstract void onItemClick(int position, long id);
 
-    public CursorLoader getLoader() {
-        return mLoader;
-    }
-
     public T getAdapter() {
         return mAdapter;
     }
@@ -137,15 +159,36 @@
     }
 
     @Override
-    protected Loader<Cursor> onCreateLoader(int id, Bundle args) {
-        return new CursorLoader(getActivity(), null, null, null, null, null);
+    protected void onInitializeLoaders() {
+        if (mProviderStatusLoader == null) {
+            mProviderStatusLoader = new ProviderStatusLoader(getActivity());
+        }
+
+        if (mSearchMode) {
+            startLoading(DIRECTORY_LOADER_ID, null);
+        } else {
+            DirectoryPartition directoryPartition = new DirectoryPartition();
+            directoryPartition.directoryId = Directory.DEFAULT;
+            directoryPartition.partitionIndex = 0;
+            mDirectoryPartitions.add(directoryPartition);
+            startLoading(false);
+        }
     }
 
     @Override
-    protected void onInitializeLoaders() {
-        mLoader = (CursorLoader)startLoading(0, null);
-        if (mProviderStatusLoader == null) {
-            mProviderStatusLoader = new ProviderStatusLoader(mLoader);
+    protected Loader<Cursor> onCreateLoader(int id, Bundle args) {
+        if (id == DIRECTORY_LOADER_ID) {
+            return new CursorLoader(getActivity(), DirectoryQuery.URI, DirectoryQuery.PROJECTION,
+                    null, null, DirectoryQuery.ORDER_BY);
+        } else {
+            CursorLoader loader = new CursorLoader(getActivity(), null, null, null, null, null);
+            if (mAdapter != null) {
+                long directoryId = args != null && args.containsKey(DIRECTORY_ID_ARG_KEY)
+                        ? args.getLong(DIRECTORY_ID_ARG_KEY)
+                        : Directory.DEFAULT;
+                mAdapter.configureLoader(loader, directoryId);
+            }
+            return loader;
         }
     }
 
@@ -155,22 +198,81 @@
             return;
         }
 
-        if (mEmptyView != null && (data == null || data.getCount() == 0)) {
-            prepareEmptyView();
-        }
+        if (loader.getId() == DIRECTORY_LOADER_ID) {
+            PackageManager pm = getActivity().getPackageManager();
+            mDirectoryPartitions.clear();
+            try {
+                while (data.moveToNext()) {
+                    DirectoryPartition partition = new DirectoryPartition();
+                    partition.directoryId = data.getLong(DirectoryQuery.ID);
+                    String packageName = data.getString(DirectoryQuery.PACKAGE_NAME);
+                    int typeResourceId = data.getInt(DirectoryQuery.TYPE_RESOURCE_ID);
+                    if (!TextUtils.isEmpty(packageName) && typeResourceId != 0) {
+                        // TODO: should this be done on a background thread?
+                        try {
+                            partition.directoryType = pm.getResourcesForApplication(packageName)
+                                    .getString(typeResourceId);
+                        } catch (Exception e) {
+                            Log.e(TAG, "Cannot obtain directory type from package: " + packageName);
+                        }
+                    }
+                    partition.displayName = data.getString(DirectoryQuery.DISPLAY_NAME);
 
-        mAdapter.changeCursor(data);
+                    // TODO obtain the "showIfEmpty" from directory meta-data
+                    partition.showIfEmpty = partition.directoryId != Directory.LOCAL_INVISIBLE;
 
-        if (data != null) {
-            showCount(data);
-            completeRestoreInstanceState();
+                    String directoryType = null;
+
+                    mDirectoryPartitions.add(partition);
+                }
+            } finally {
+                data.close();
+            }
+
+            mAdapter.resetPartitions();
+            int size = mDirectoryPartitions.size();
+            for (int i = 0; i < size; i++) {
+                DirectoryPartition partition = mDirectoryPartitions.get(i);
+                partition.partitionIndex = i;
+                mAdapter.addDirectoryPartition(partition);
+            }
+
+            startLoading(true);
+        } else {
+            int partitionIndex = loader.getId();
+
+            if (mEmptyView != null && (data == null || data.getCount() == 0)) {
+                prepareEmptyView();
+            }
+
+            mAdapter.changeCursor(partitionIndex, data);
+
+            if (data != null) {
+                showCount(partitionIndex, data);
+                completeRestoreInstanceState();
+            }
         }
     }
 
     protected void reloadData() {
+        startLoading(true);
+    }
+
+    protected void startLoading(boolean forceLoad) {
         configureAdapter();
-        mAdapter.configureLoader(mLoader);
-        mLoader.forceLoad();
+        for (DirectoryPartition partition : mDirectoryPartitions) {
+            CursorLoader loader = (CursorLoader)getLoader(partition.partitionIndex);
+            if (loader == null) {
+                Bundle args = new Bundle();
+                args.putLong(DIRECTORY_ID_ARG_KEY, partition.directoryId);
+                startLoading(partition.partitionIndex, args);
+            } else {
+                mAdapter.configureLoader(loader, partition.directoryId);
+                if (forceLoad) {
+                    loader.forceLoad();
+                }
+            }
+        }
     }
 
     /**
@@ -184,7 +286,7 @@
      * Shows the count of entries included in the list. The default
      * implementation does nothing.
      */
-    protected void showCount(Cursor data) {
+    protected void showCount(int partitionIndex, Cursor data) {
     }
 
     /**
@@ -295,8 +397,7 @@
         }
 
         loadPreferences(mContactsPrefs);
-        configureAdapter();
-        mAdapter.configureLoader(mLoader);
+        startLoading(false);
 
         ContactEntryListView listView = (ContactEntryListView)mListView;
         listView.setHighlightNamesWhenScrolling(isNameHighlighingEnabled());
@@ -579,7 +680,7 @@
                             case ProviderStatus.STATUS_NORMAL:
                                 mAdapter.notifyDataSetInvalidated();
                                 if (loadData) {
-                                    mLoader.forceLoad();
+                                    reloadData();
                                 }
                                 break;
 
diff --git a/src/com/android/contacts/list/DefaultContactBrowseListFragment.java b/src/com/android/contacts/list/DefaultContactBrowseListFragment.java
index 3dd80df..c38adba 100644
--- a/src/com/android/contacts/list/DefaultContactBrowseListFragment.java
+++ b/src/com/android/contacts/list/DefaultContactBrowseListFragment.java
@@ -79,18 +79,14 @@
     @Override
     protected void onItemClick(int position, long id) {
         ContactListAdapter adapter = getAdapter();
-        if (adapter.isSearchAllContactsItemPosition(position)) {
-            searchAllContacts();
-        } else {
-            if (isEditMode()) {
-                if (position == 0 && !isSearchMode() && isCreateContactEnabled()) {
-                    createNewContact();
-                } else {
-                    editContact(adapter.getContactUri(position));
-                }
+        if (isEditMode()) {
+            if (position == 0 && !isSearchMode() && isCreateContactEnabled()) {
+                createNewContact();
             } else {
-                viewContact(adapter.getContactUri(position));
+                editContact(adapter.getContactUri(position));
             }
+        } else {
+            viewContact(adapter.getContactUri(position));
         }
     }
 
@@ -126,29 +122,21 @@
     @Override
     protected void onCreateView(LayoutInflater inflater, ViewGroup container) {
         super.onCreateView(inflater, container);
-        if (!isSearchResultsMode()) {
+        if (!isSearchMode() && !isSearchResultsMode()) {
             // In the search-results mode the count is shown in the fat header above the list
             getListView().addHeaderView(inflater.inflate(R.layout.total_contacts, null, false));
         }
     }
 
     @Override
-    protected void showCount(Cursor data) {
+    protected void showCount(int partitionIndex, Cursor data) {
         int count = data.getCount();
-        if (isSearchMode()) {
-            TextView textView = (TextView) getView().findViewById(R.id.totalContactsText);
-            // TODO
-            // if (TextUtils.isEmpty(getQueryString())) {
-            String text = getQuantityText(count, R.string.listFoundAllContactsZero,
-                    R.plurals.searchFoundContacts);
-            textView.setText(text);
-        }
-        else if (isSearchResultsMode()) {
+        if (isSearchResultsMode()) {
             TextView countText = (TextView)getView().findViewById(R.id.search_results_found);
             String text = getQuantityText(data.getCount(),
                     R.string.listFoundAllContactsZero, R.plurals.listFoundAllContacts);
             countText.setText(text);
-        } else {
+        } else if (!isSearchMode()){
             // TODO
             // if (contactsListActivity.mDisplayOnlyPhones) {
             // text = contactsListActivity.getQuantityText(count,
diff --git a/src/com/android/contacts/list/DefaultContactListAdapter.java b/src/com/android/contacts/list/DefaultContactListAdapter.java
index 24c493a..6819a6a 100644
--- a/src/com/android/contacts/list/DefaultContactListAdapter.java
+++ b/src/com/android/contacts/list/DefaultContactListAdapter.java
@@ -19,8 +19,10 @@
 import android.content.CursorLoader;
 import android.database.Cursor;
 import android.net.Uri;
+import android.net.Uri.Builder;
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.Contacts;
+import android.provider.ContactsContract.Directory;
 import android.text.TextUtils;
 import android.view.View;
 
@@ -45,39 +47,51 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         Uri uri;
 
-        if (isSearchMode() || isSearchResultsMode()) {
+        if (isSearchMode()) {
             String query = getQueryString();
-            uri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
-                    TextUtils.isEmpty(query) ? "" : Uri.encode(query));
+            Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon();
+            if (TextUtils.isEmpty(query)) {
+                builder.appendPath("");
+            } else {
+                builder.appendPath(query);      // Builder will encode the query
+            }
+
+            builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
+                    String.valueOf(directoryId));
+            uri = builder.build();
             loader.setProjection(FILTER_PROJECTION);
         } else {
             uri = Contacts.CONTENT_URI;
             loader.setProjection(PROJECTION);
         }
 
-        if (mVisibleContactsOnly && mContactsWithPhoneNumbersOnly) {
-            loader.setSelection(Contacts.IN_VISIBLE_GROUP + "=1"
-                    + " AND " + Contacts.HAS_PHONE_NUMBER + "=1");
-        } else if (mVisibleContactsOnly) {
-            loader.setSelection(Contacts.IN_VISIBLE_GROUP + "=1");
-        } else if (mContactsWithPhoneNumbersOnly) {
-            loader.setSelection(Contacts.HAS_PHONE_NUMBER + "=1");
-        }
-
-        if (isSectionHeaderDisplayEnabled()) {
-            uri = buildSectionIndexerUri(uri);
+        if (directoryId == Directory.DEFAULT) {
+            if (mVisibleContactsOnly && mContactsWithPhoneNumbersOnly) {
+                loader.setSelection(Contacts.IN_VISIBLE_GROUP + "=1"
+                        + " AND " + Contacts.HAS_PHONE_NUMBER + "=1");
+            } else if (mVisibleContactsOnly) {
+                loader.setSelection(Contacts.IN_VISIBLE_GROUP + "=1");
+            } else if (mContactsWithPhoneNumbersOnly) {
+                loader.setSelection(Contacts.HAS_PHONE_NUMBER + "=1");
+            }
+            if (isSectionHeaderDisplayEnabled()) {
+                uri = buildSectionIndexerUri(uri);
+            }
         }
 
         loader.setUri(uri);
 
+        String sortOrder;
         if (getSortOrder() == ContactsContract.Preferences.SORT_ORDER_PRIMARY) {
-            loader.setSortOrder(Contacts.SORT_KEY_PRIMARY);
+            sortOrder = Contacts.SORT_KEY_PRIMARY;
         } else {
-            loader.setSortOrder(Contacts.SORT_KEY_ALTERNATIVE);
+            sortOrder = Contacts.SORT_KEY_ALTERNATIVE;
         }
+
+        loader.setSortOrder(sortOrder);
     }
 
     @Override
diff --git a/src/com/android/contacts/list/DirectoryPartition.java b/src/com/android/contacts/list/DirectoryPartition.java
new file mode 100644
index 0000000..1e8b3a7
--- /dev/null
+++ b/src/com/android/contacts/list/DirectoryPartition.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.contacts.list;
+
+import android.provider.ContactsContract.Directory;
+
+/**
+ * Model object for a {@link Directory} row.
+ */
+public final class DirectoryPartition {
+
+    /**
+     * Directory ID, see {@link Directory}.
+     */
+    long directoryId;
+
+    /**
+     * Corresponding loader ID.
+     */
+    int partitionIndex;
+
+    /**
+     * Directory type resolved from {@link Directory#PACKAGE_NAME} and
+     * {@link Directory#TYPE_RESOURCE_ID};
+     */
+    public String directoryType;
+
+    /**
+     * See {@link Directory#DISPLAY_NAME}.
+     */
+    public String displayName;
+
+    /**
+     * True if the directory should be shown even if no contacts are found.
+     */
+    public boolean showIfEmpty;
+
+}
\ No newline at end of file
diff --git a/src/com/android/contacts/list/JoinContactListAdapter.java b/src/com/android/contacts/list/JoinContactListAdapter.java
index 4228b0c..6258be4 100644
--- a/src/com/android/contacts/list/JoinContactListAdapter.java
+++ b/src/com/android/contacts/list/JoinContactListAdapter.java
@@ -78,7 +78,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader cursorLoader) {
+    public void configureLoader(CursorLoader cursorLoader, long directoryId) {
         JoinContactLoader loader = (JoinContactLoader)cursorLoader;
         loader.setLoadSuggestionsAndAllContacts(mAllContactsListShown);
 
diff --git a/src/com/android/contacts/list/LegacyContactListAdapter.java b/src/com/android/contacts/list/LegacyContactListAdapter.java
index 34ae708..39c0b53 100644
--- a/src/com/android/contacts/list/LegacyContactListAdapter.java
+++ b/src/com/android/contacts/list/LegacyContactListAdapter.java
@@ -52,7 +52,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         loader.setUri(People.CONTENT_URI);
         loader.setProjection(PEOPLE_PROJECTION);
         loader.setSortOrder(People.DISPLAY_NAME);
diff --git a/src/com/android/contacts/list/LegacyPhoneNumberListAdapter.java b/src/com/android/contacts/list/LegacyPhoneNumberListAdapter.java
index ed53ef8..47747fb 100644
--- a/src/com/android/contacts/list/LegacyPhoneNumberListAdapter.java
+++ b/src/com/android/contacts/list/LegacyPhoneNumberListAdapter.java
@@ -56,7 +56,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         loader.setUri(Phones.CONTENT_URI);
         loader.setProjection(PHONES_PROJECTION);
         loader.setSortOrder(Phones.DISPLAY_NAME);
diff --git a/src/com/android/contacts/list/LegacyPostalAddressListAdapter.java b/src/com/android/contacts/list/LegacyPostalAddressListAdapter.java
index 36df18b..3796c62 100644
--- a/src/com/android/contacts/list/LegacyPostalAddressListAdapter.java
+++ b/src/com/android/contacts/list/LegacyPostalAddressListAdapter.java
@@ -56,7 +56,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         loader.setUri(ContactMethods.CONTENT_URI);
         loader.setProjection(POSTALS_PROJECTION);
         loader.setSortOrder(People.DISPLAY_NAME);
diff --git a/src/com/android/contacts/list/PhoneNumberListAdapter.java b/src/com/android/contacts/list/PhoneNumberListAdapter.java
index 2894ed6..617e823 100644
--- a/src/com/android/contacts/list/PhoneNumberListAdapter.java
+++ b/src/com/android/contacts/list/PhoneNumberListAdapter.java
@@ -69,7 +69,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         loader.setUri(buildSectionIndexerUri(Phone.CONTENT_URI));
         loader.setProjection(PHONES_PROJECTION);
 
diff --git a/src/com/android/contacts/list/PostalAddressListAdapter.java b/src/com/android/contacts/list/PostalAddressListAdapter.java
index b6f8fc4..797089c 100644
--- a/src/com/android/contacts/list/PostalAddressListAdapter.java
+++ b/src/com/android/contacts/list/PostalAddressListAdapter.java
@@ -61,7 +61,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         loader.setUri(buildSectionIndexerUri(StructuredPostal.CONTENT_URI));
         loader.setProjection(POSTALS_PROJECTION);
 
diff --git a/src/com/android/contacts/list/ProviderStatusLoader.java b/src/com/android/contacts/list/ProviderStatusLoader.java
index 1da32d0..2eb9672 100644
--- a/src/com/android/contacts/list/ProviderStatusLoader.java
+++ b/src/com/android/contacts/list/ProviderStatusLoader.java
@@ -15,44 +15,25 @@
  */
 package com.android.contacts.list;
 
-import com.android.contacts.ContactsUtils;
-import com.android.contacts.PhoneDisambigDialog;
-import com.android.contacts.R;
-
-import android.app.LoaderManagingFragment;
-import android.content.AsyncQueryHandler;
-import android.content.ContentValues;
 import android.content.Context;
-import android.content.CursorLoader;
-import android.content.Intent;
 import android.database.Cursor;
-import android.net.Uri;
-import android.provider.Settings;
-import android.provider.ContactsContract.Contacts;
 import android.provider.ContactsContract.ProviderStatus;
-import android.provider.ContactsContract.RawContacts;
-import android.provider.ContactsContract.CommonDataKinds.Phone;
-import android.provider.ContactsContract.Contacts.Data;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.TextView;
 
 /**
  * Checks provider status and configures a list adapter accordingly.
  */
 public class ProviderStatusLoader {
 
-    private final CursorLoader mLoader;
+    private final Context mContext;
 
-    public ProviderStatusLoader(CursorLoader loader) {
-        this.mLoader = loader;
+    public ProviderStatusLoader(Context context) {
+        this.mContext = context;
     }
 
     public int getProviderStatus() {
         // This query can be performed on the UI thread because
         // the API explicitly allows such use.
-        Cursor cursor = mLoader.getContext().getContentResolver().query(
+        Cursor cursor = mContext.getContentResolver().query(
                 ProviderStatus.CONTENT_URI,
                 new String[] { ProviderStatus.STATUS, ProviderStatus.DATA1 }, null, null, null);
         if (cursor != null) {
diff --git a/src/com/android/contacts/list/StrequentContactListAdapter.java b/src/com/android/contacts/list/StrequentContactListAdapter.java
index 757e3e7..4a72f63 100644
--- a/src/com/android/contacts/list/StrequentContactListAdapter.java
+++ b/src/com/android/contacts/list/StrequentContactListAdapter.java
@@ -60,7 +60,7 @@
     }
 
     @Override
-    public void configureLoader(CursorLoader loader) {
+    public void configureLoader(CursorLoader loader, long directoryId) {
         String sortOrder = getSortOrder() == ContactsContract.Preferences.SORT_ORDER_PRIMARY
                 ? Contacts.SORT_KEY_PRIMARY
                 : Contacts.SORT_KEY_ALTERNATIVE;
diff --git a/src/com/android/contacts/widget/CompositeCursorAdapter.java b/src/com/android/contacts/widget/CompositeCursorAdapter.java
index d917155..58f071a 100644
--- a/src/com/android/contacts/widget/CompositeCursorAdapter.java
+++ b/src/com/android/contacts/widget/CompositeCursorAdapter.java
@@ -76,6 +76,13 @@
         }
         mPartitions[mSize++] = new Partition(showIfEmpty, hasHeader);
         invalidate();
+        notifyDataSetChanged();
+    }
+
+    public void resetPartitions() {
+        mSize = 0;
+        invalidate();
+        notifyDataSetChanged();
     }
 
     protected void invalidate() {
@@ -91,11 +98,6 @@
             return;
         }
 
-        if (mSize == 0) {
-            throw new IllegalStateException("A CompositeCursorAdapter should have "
-                    + "at least one partition");
-        }
-
         mCount = 0;
         for (int i = 0; i < mSize; i++) {
             Cursor cursor = mPartitions[i].cursor;
@@ -128,6 +130,13 @@
     }
 
     /**
+     * Returns the cursor for the given partition
+     */
+    public Cursor getCursor(int partition) {
+        return mPartitions[partition].cursor;
+    }
+
+    /**
      * Changes the cursor for an individual partition.
      */
     public void changeCursor(int partition, Cursor cursor) {
diff --git a/src/com/android/contacts/widget/IndexerListAdapter.java b/src/com/android/contacts/widget/IndexerListAdapter.java
index 783ef8d..d68b3e6 100644
--- a/src/com/android/contacts/widget/IndexerListAdapter.java
+++ b/src/com/android/contacts/widget/IndexerListAdapter.java
@@ -111,13 +111,15 @@
     }
 
     @Override
-    public View createPinnedHeaderView(int viewIndex, ViewGroup parent) {
+    public View getPinnedHeaderView(int viewIndex, View convertView, ViewGroup parent) {
         if (isSectionHeaderDisplayEnabled() && viewIndex == getPinnedHeaderCount() - 1) {
-            mHeader = LayoutInflater.from(mContext).
-                    inflate(mSectionHeaderLayoutResId, parent, false);
+            if (mHeader == null) {
+                mHeader = LayoutInflater.from(mContext).
+                        inflate(mSectionHeaderLayoutResId, parent, false);
+            }
             return mHeader;
         } else {
-            return super.createPinnedHeaderView(viewIndex, parent);
+            return super.getPinnedHeaderView(viewIndex, convertView, parent);
         }
     }
 
diff --git a/src/com/android/contacts/widget/PinnedHeaderListAdapter.java b/src/com/android/contacts/widget/PinnedHeaderListAdapter.java
index 88ab3db..1ed96c0 100644
--- a/src/com/android/contacts/widget/PinnedHeaderListAdapter.java
+++ b/src/com/android/contacts/widget/PinnedHeaderListAdapter.java
@@ -61,12 +61,15 @@
      * The default implementation creates the same type of view as a normal
      * partition header.
      */
-    public View createPinnedHeaderView(int partition, ViewGroup parent) {
+    public View getPinnedHeaderView(int partition, View convertView, ViewGroup parent) {
         if (hasHeader(partition)) {
-            View view = newHeaderView(getContext(), partition, null, parent);
-            view.setFocusable(false);
-            view.setEnabled(false);
-            bindHeaderView(view, partition, null);
+            View view = convertView;
+            if (view == null) {
+                view = newHeaderView(getContext(), partition, null, parent);
+                view.setFocusable(false);
+                view.setEnabled(false);
+            }
+            bindHeaderView(view, partition, getCursor(partition));
             return view;
         } else {
             return null;
diff --git a/src/com/android/contacts/widget/PinnedHeaderListDemoActivity.java b/src/com/android/contacts/widget/PinnedHeaderListDemoActivity.java
index 66b70f3..b553e3f 100644
--- a/src/com/android/contacts/widget/PinnedHeaderListDemoActivity.java
+++ b/src/com/android/contacts/widget/PinnedHeaderListDemoActivity.java
@@ -77,7 +77,7 @@
         }
 
         @Override
-        public View createPinnedHeaderView(int viewIndex, ViewGroup parent) {
+        public View getPinnedHeaderView(int viewIndex, View convertView, ViewGroup parent) {
             LayoutInflater inflater = LayoutInflater.from(getContext());
             View view = inflater.inflate(R.layout.list_section, parent, false);
             view.setFocusable(false);
diff --git a/src/com/android/contacts/widget/PinnedHeaderListView.java b/src/com/android/contacts/widget/PinnedHeaderListView.java
index 9ed51d8..fa6eaab 100644
--- a/src/com/android/contacts/widget/PinnedHeaderListView.java
+++ b/src/com/android/contacts/widget/PinnedHeaderListView.java
@@ -48,9 +48,9 @@
         int getPinnedHeaderCount();
 
         /**
-         * Creates the pinned header view.
+         * Creates or updates the pinned header view.
          */
-        View createPinnedHeaderView(int viewIndex, ViewGroup parent);
+        View getPinnedHeaderView(int viewIndex, View convertView, ViewGroup parent);
 
         /**
          * Configures the pinned headers to match the visible list items. The
@@ -78,6 +78,7 @@
     }
 
     private PinnedHeaderAdapter mAdapter;
+    private int mSize;
     private PinnedHeader[] mHeaders;
     private int mPinnedHeaderBackgroundColor;
     private RectF mBounds = new RectF();
@@ -113,24 +114,8 @@
 
     @Override
     public void setAdapter(ListAdapter adapter) {
-        super.setAdapter(adapter);
         mAdapter = (PinnedHeaderAdapter)adapter;
-        int count = mAdapter.getPinnedHeaderCount();
-        mHeaders = new PinnedHeader[count];
-        for (int i = 0; i < count; i++) {
-            PinnedHeader header = new PinnedHeader();
-            header.view = mAdapter.createPinnedHeaderView(i, this);
-            mHeaders[i] = header;
-        }
-
-        // Disable vertical fading when the pinned header is present
-        // TODO change ListView to allow separate measures for top and bottom fading edge;
-        // in this particular case we would like to disable the top, but not the bottom edge.
-        if (count > 0) {
-            setFadingEdgeLength(0);
-        }
-
-        requestLayout();
+        super.setAdapter(adapter);
     }
 
     @Override
@@ -148,6 +133,32 @@
     public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
             int totalItemCount) {
         if (mAdapter != null) {
+            int count = mAdapter.getPinnedHeaderCount();
+            if (count != mSize) {
+                mSize = count;
+                if (mHeaders == null) {
+                    mHeaders = new PinnedHeader[mSize];
+                } else if (mHeaders.length < mSize) {
+                    PinnedHeader[] headers = mHeaders;
+                    mHeaders = new PinnedHeader[mSize];
+                    System.arraycopy(headers, 0, mHeaders, 0, headers.length);
+                }
+            }
+
+            for (int i = 0; i < mSize; i++) {
+                if (mHeaders[i] == null) {
+                    mHeaders[i] = new PinnedHeader();
+                }
+                mHeaders[i].view = mAdapter.getPinnedHeaderView(i, mHeaders[i].view, this);
+            }
+
+            // Disable vertical fading when the pinned header is present
+            // TODO change ListView to allow separate measures for top and bottom fading edge;
+            // in this particular case we would like to disable the top, but not the bottom edge.
+            if (mSize > 0) {
+                setFadingEdgeLength(0);
+            }
+
             mAdapter.configurePinnedHeaders(this);
         }
         if (mOnScrollListener != null) {
@@ -172,7 +183,7 @@
         int windowBottom = height;
 
         int prevHeaderBottom = 0;
-        for (int i = 0; i < mHeaders.length; i++) {
+        for (int i = 0; i < mSize; i++) {
             PinnedHeader header = mHeaders[i];
             if (header.visible) {
                 if (header.state == TOP) {
@@ -271,8 +282,15 @@
     private void ensurePinnedHeaderLayout(int viewIndex) {
         View view = mHeaders[viewIndex].view;
         if (view.isLayoutRequested()) {
-            view.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
-                    MeasureSpec.UNSPECIFIED);
+            int widthSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY);
+            int heightSpec;
+            int lpHeight = view.getLayoutParams().height;
+            if (lpHeight > 0) {
+                heightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
+            } else {
+                heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
+            }
+            view.measure(widthSpec, heightSpec);
             int height = view.getMeasuredHeight();
             mHeaders[viewIndex].height = height;
             view.layout(0, 0, view.getMeasuredWidth(), height);
@@ -283,7 +301,7 @@
      * Returns the sum of heights of headers pinned to the top.
      */
     public int getTotalTopPinnedHeaderHeight() {
-        for (int i = mHeaders.length; --i >= 0;) {
+        for (int i = mSize; --i >= 0;) {
             PinnedHeader header = mHeaders[i];
             if (header.visible && header.state == TOP) {
                 return header.y + header.height;
@@ -311,7 +329,7 @@
     @Override
     protected void dispatchDraw(Canvas canvas) {
         super.dispatchDraw(canvas);
-        for (int i = mHeaders.length; --i >= 0;) {
+        for (int i = mSize; --i >= 0;) {
             PinnedHeader header = mHeaders[i];
             if (header.visible) {
                 View view = header.view;