Home | History | Annotate | Download | only in app
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.example.android.apis.app;
     18 
     19 import android.app.Activity;
     20 import android.app.FragmentManager;
     21 import android.app.ListFragment;
     22 import android.app.LoaderManager;
     23 import android.content.CursorLoader;
     24 import android.content.Loader;
     25 import android.database.Cursor;
     26 import android.net.Uri;
     27 import android.os.Bundle;
     28 import android.provider.ContactsContract.Contacts;
     29 import android.text.TextUtils;
     30 import android.util.Log;
     31 import android.view.Menu;
     32 import android.view.MenuInflater;
     33 import android.view.MenuItem;
     34 import android.view.View;
     35 import android.widget.ListView;
     36 import android.widget.SearchView;
     37 import android.widget.SimpleCursorAdapter;
     38 import android.widget.SearchView.OnQueryTextListener;
     39 
     40 /**
     41  * Demonstration of the use of a CursorLoader to load and display contacts
     42  * data in a fragment.
     43  */
     44 public class LoaderCursor extends Activity {
     45 
     46     @Override
     47     protected void onCreate(Bundle savedInstanceState) {
     48         super.onCreate(savedInstanceState);
     49 
     50         FragmentManager fm = getFragmentManager();
     51 
     52         // Create the list fragment and add it as our sole content.
     53         if (fm.findFragmentById(android.R.id.content) == null) {
     54             CursorLoaderListFragment list = new CursorLoaderListFragment();
     55             fm.beginTransaction().add(android.R.id.content, list).commit();
     56         }
     57     }
     58 
     59 //BEGIN_INCLUDE(fragment_cursor)
     60     public static class CursorLoaderListFragment extends ListFragment
     61             implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
     62 
     63         // This is the Adapter being used to display the list's data.
     64         SimpleCursorAdapter mAdapter;
     65 
     66         // If non-null, this is the current filter the user has provided.
     67         String mCurFilter;
     68 
     69         @Override public void onActivityCreated(Bundle savedInstanceState) {
     70             super.onActivityCreated(savedInstanceState);
     71 
     72             // Give some text to display if there is no data.  In a real
     73             // application this would come from a resource.
     74             setEmptyText("No phone numbers");
     75 
     76             // We have a menu item to show in action bar.
     77             setHasOptionsMenu(true);
     78 
     79             // Create an empty adapter we will use to display the loaded data.
     80             mAdapter = new SimpleCursorAdapter(getActivity(),
     81                     android.R.layout.simple_list_item_2, null,
     82                     new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
     83                     new int[] { android.R.id.text1, android.R.id.text2 }, 0);
     84             setListAdapter(mAdapter);
     85 
     86             // Start out with a progress indicator.
     87             setListShown(false);
     88 
     89             // Prepare the loader.  Either re-connect with an existing one,
     90             // or start a new one.
     91             getLoaderManager().initLoader(0, null, this);
     92         }
     93 
     94         @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     95             // Place an action bar item for searching.
     96             MenuItem item = menu.add("Search");
     97             item.setIcon(android.R.drawable.ic_menu_search);
     98             item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
     99                     | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    100             SearchView sv = new SearchView(getActivity());
    101             sv.setOnQueryTextListener(this);
    102             item.setActionView(sv);
    103         }
    104 
    105         public boolean onQueryTextChange(String newText) {
    106             // Called when the action bar search text has changed.  Update
    107             // the search filter, and restart the loader to do a new query
    108             // with this filter.
    109             String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
    110             // Don't do anything if the filter hasn't actually changed.
    111             // Prevents restarting the loader when restoring state.
    112             if (mCurFilter == null && newFilter == null) {
    113                 return true;
    114             }
    115             if (mCurFilter != null && mCurFilter.equals(newFilter)) {
    116                 return true;
    117             }
    118             mCurFilter = newFilter;
    119             getLoaderManager().restartLoader(0, null, this);
    120             return true;
    121         }
    122 
    123         @Override public boolean onQueryTextSubmit(String query) {
    124             // Don't care about this.
    125             return true;
    126         }
    127 
    128         @Override public void onListItemClick(ListView l, View v, int position, long id) {
    129             // Insert desired behavior here.
    130             Log.i("FragmentComplexList", "Item clicked: " + id);
    131         }
    132 
    133         // These are the Contacts rows that we will retrieve.
    134         static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
    135             Contacts._ID,
    136             Contacts.DISPLAY_NAME,
    137             Contacts.CONTACT_STATUS,
    138             Contacts.CONTACT_PRESENCE,
    139             Contacts.PHOTO_ID,
    140             Contacts.LOOKUP_KEY,
    141         };
    142 
    143         public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    144             // This is called when a new Loader needs to be created.  This
    145             // sample only has one Loader, so we don't care about the ID.
    146             // First, pick the base URI to use depending on whether we are
    147             // currently filtering.
    148             Uri baseUri;
    149             if (mCurFilter != null) {
    150                 baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
    151                         Uri.encode(mCurFilter));
    152             } else {
    153                 baseUri = Contacts.CONTENT_URI;
    154             }
    155 
    156             // Now create and return a CursorLoader that will take care of
    157             // creating a Cursor for the data being displayed.
    158             String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
    159                     + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
    160                     + Contacts.DISPLAY_NAME + " != '' ))";
    161             return new CursorLoader(getActivity(), baseUri,
    162                     CONTACTS_SUMMARY_PROJECTION, select, null,
    163                     Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    164         }
    165 
    166         public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    167             // Swap the new cursor in.  (The framework will take care of closing the
    168             // old cursor once we return.)
    169             mAdapter.swapCursor(data);
    170 
    171             // The list should now be shown.
    172             if (isResumed()) {
    173                 setListShown(true);
    174             } else {
    175                 setListShownNoAnimation(true);
    176             }
    177         }
    178 
    179         public void onLoaderReset(Loader<Cursor> loader) {
    180             // This is called when the last Cursor provided to onLoadFinished()
    181             // above is about to be closed.  We need to make sure we are no
    182             // longer using it.
    183             mAdapter.swapCursor(null);
    184         }
    185     }
    186 //END_INCLUDE(fragment_cursor)
    187 }
    188