Home | History | Annotate | Download | only in app
      1 /*
      2  * Copyright (C) 2012 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 LoaderRetained 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             // In this sample we are going to use a retained fragment.
     73             setRetainInstance(true);
     74 
     75             // Give some text to display if there is no data.  In a real
     76             // application this would come from a resource.
     77             setEmptyText("No phone numbers");
     78 
     79             // We have a menu item to show in action bar.
     80             setHasOptionsMenu(true);
     81 
     82             // Create an empty adapter we will use to display the loaded data.
     83             mAdapter = new SimpleCursorAdapter(getActivity(),
     84                     android.R.layout.simple_list_item_2, null,
     85                     new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
     86                     new int[] { android.R.id.text1, android.R.id.text2 }, 0);
     87             setListAdapter(mAdapter);
     88 
     89             // Start out with a progress indicator.
     90             setListShown(false);
     91 
     92             // Prepare the loader.  Either re-connect with an existing one,
     93             // or start a new one.
     94             getLoaderManager().initLoader(0, null, this);
     95         }
     96 
     97         @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     98             // Place an action bar item for searching.
     99             MenuItem item = menu.add("Search");
    100             item.setIcon(android.R.drawable.ic_menu_search);
    101             item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
    102                     | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    103             SearchView sv = new SearchView(getActivity());
    104             sv.setOnQueryTextListener(this);
    105             item.setActionView(sv);
    106         }
    107 
    108         public boolean onQueryTextChange(String newText) {
    109             // Called when the action bar search text has changed.  Update
    110             // the search filter, and restart the loader to do a new query
    111             // with this filter.
    112             String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
    113             // Don't do anything if the filter hasn't actually changed.
    114             // Prevents restarting the loader when restoring state.
    115             if (mCurFilter == null && newFilter == null) {
    116                 return true;
    117             }
    118             if (mCurFilter != null && mCurFilter.equals(newFilter)) {
    119                 return true;
    120             }
    121             mCurFilter = newFilter;
    122             getLoaderManager().restartLoader(0, null, this);
    123             return true;
    124         }
    125 
    126         @Override public boolean onQueryTextSubmit(String query) {
    127             // Don't care about this.
    128             return true;
    129         }
    130 
    131         @Override public void onListItemClick(ListView l, View v, int position, long id) {
    132             // Insert desired behavior here.
    133             Log.i("FragmentComplexList", "Item clicked: " + id);
    134         }
    135 
    136         // These are the Contacts rows that we will retrieve.
    137         static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
    138             Contacts._ID,
    139             Contacts.DISPLAY_NAME,
    140             Contacts.CONTACT_STATUS,
    141             Contacts.CONTACT_PRESENCE,
    142             Contacts.PHOTO_ID,
    143             Contacts.LOOKUP_KEY,
    144         };
    145 
    146         public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    147             // This is called when a new Loader needs to be created.  This
    148             // sample only has one Loader, so we don't care about the ID.
    149             // First, pick the base URI to use depending on whether we are
    150             // currently filtering.
    151             Uri baseUri;
    152             if (mCurFilter != null) {
    153                 baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
    154                         Uri.encode(mCurFilter));
    155             } else {
    156                 baseUri = Contacts.CONTENT_URI;
    157             }
    158 
    159             // Now create and return a CursorLoader that will take care of
    160             // creating a Cursor for the data being displayed.
    161             String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
    162                     + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
    163                     + Contacts.DISPLAY_NAME + " != '' ))";
    164             return new CursorLoader(getActivity(), baseUri,
    165                     CONTACTS_SUMMARY_PROJECTION, select, null,
    166                     Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    167         }
    168 
    169         public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    170             // Swap the new cursor in.  (The framework will take care of closing the
    171             // old cursor once we return.)
    172             mAdapter.swapCursor(data);
    173 
    174             // The list should now be shown.
    175             if (isResumed()) {
    176                 setListShown(true);
    177             } else {
    178                 setListShownNoAnimation(true);
    179             }
    180         }
    181 
    182         public void onLoaderReset(Loader<Cursor> loader) {
    183             // This is called when the last Cursor provided to onLoadFinished()
    184             // above is about to be closed.  We need to make sure we are no
    185             // longer using it.
    186             mAdapter.swapCursor(null);
    187         }
    188     }
    189 //END_INCLUDE(fragment_cursor)
    190 }
    191