• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.Context;
24 import android.content.CursorLoader;
25 import android.content.Loader;
26 import android.database.Cursor;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.provider.ContactsContract.Contacts;
30 import android.text.TextUtils;
31 import android.util.Log;
32 import android.view.Menu;
33 import android.view.MenuInflater;
34 import android.view.MenuItem;
35 import android.view.View;
36 import android.widget.ListView;
37 import android.widget.SearchView;
38 import android.widget.SearchView.OnCloseListener;
39 import android.widget.SimpleCursorAdapter;
40 import android.widget.SearchView.OnQueryTextListener;
41 
42 /**
43  * Demonstration of the use of a CursorLoader to load and display contacts
44  * data in a fragment.
45  */
46 public class LoaderCursor extends Activity {
47 
48     @Override
onCreate(Bundle savedInstanceState)49     protected void onCreate(Bundle savedInstanceState) {
50         super.onCreate(savedInstanceState);
51 
52         FragmentManager fm = getFragmentManager();
53 
54         // Create the list fragment and add it as our sole content.
55         if (fm.findFragmentById(android.R.id.content) == null) {
56             CursorLoaderListFragment list = new CursorLoaderListFragment();
57             fm.beginTransaction().add(android.R.id.content, list).commit();
58         }
59     }
60 
61 //BEGIN_INCLUDE(fragment_cursor)
62     public static class CursorLoaderListFragment extends ListFragment
63             implements OnQueryTextListener, OnCloseListener,
64             LoaderManager.LoaderCallbacks<Cursor> {
65 
66         // This is the Adapter being used to display the list's data.
67         SimpleCursorAdapter mAdapter;
68 
69         // The SearchView for doing filtering.
70         SearchView mSearchView;
71 
72         // If non-null, this is the current filter the user has provided.
73         String mCurFilter;
74 
onActivityCreated(Bundle savedInstanceState)75         @Override public void onActivityCreated(Bundle savedInstanceState) {
76             super.onActivityCreated(savedInstanceState);
77 
78             // Give some text to display if there is no data.  In a real
79             // application this would come from a resource.
80             setEmptyText("No phone numbers");
81 
82             // We have a menu item to show in action bar.
83             setHasOptionsMenu(true);
84 
85             // Create an empty adapter we will use to display the loaded data.
86             mAdapter = new SimpleCursorAdapter(getActivity(),
87                     android.R.layout.simple_list_item_2, null,
88                     new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
89                     new int[] { android.R.id.text1, android.R.id.text2 }, 0);
90             setListAdapter(mAdapter);
91 
92             // Start out with a progress indicator.
93             setListShown(false);
94 
95             // Prepare the loader.  Either re-connect with an existing one,
96             // or start a new one.
97             getLoaderManager().initLoader(0, null, this);
98         }
99 
100         public static class MySearchView extends SearchView {
MySearchView(Context context)101             public MySearchView(Context context) {
102                 super(context);
103             }
104 
105             // The normal SearchView doesn't clear its search text when
106             // collapsed, so we will do this for it.
107             @Override
onActionViewCollapsed()108             public void onActionViewCollapsed() {
109                 setQuery("", false);
110                 super.onActionViewCollapsed();
111             }
112         }
113 
onCreateOptionsMenu(Menu menu, MenuInflater inflater)114         @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
115             // Place an action bar item for searching.
116             MenuItem item = menu.add("Search");
117             item.setIcon(android.R.drawable.ic_menu_search);
118             item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
119                     | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
120             mSearchView = new MySearchView(getActivity());
121             mSearchView.setOnQueryTextListener(this);
122             mSearchView.setOnCloseListener(this);
123             mSearchView.setIconifiedByDefault(true);
124             item.setActionView(mSearchView);
125         }
126 
onQueryTextChange(String newText)127         public boolean onQueryTextChange(String newText) {
128             // Called when the action bar search text has changed.  Update
129             // the search filter, and restart the loader to do a new query
130             // with this filter.
131             String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
132             // Don't do anything if the filter hasn't actually changed.
133             // Prevents restarting the loader when restoring state.
134             if (mCurFilter == null && newFilter == null) {
135                 return true;
136             }
137             if (mCurFilter != null && mCurFilter.equals(newFilter)) {
138                 return true;
139             }
140             mCurFilter = newFilter;
141             getLoaderManager().restartLoader(0, null, this);
142             return true;
143         }
144 
onQueryTextSubmit(String query)145         @Override public boolean onQueryTextSubmit(String query) {
146             // Don't care about this.
147             return true;
148         }
149 
150         @Override
onClose()151         public boolean onClose() {
152             if (!TextUtils.isEmpty(mSearchView.getQuery())) {
153                 mSearchView.setQuery(null, true);
154             }
155             return true;
156         }
157 
onListItemClick(ListView l, View v, int position, long id)158         @Override public void onListItemClick(ListView l, View v, int position, long id) {
159             // Insert desired behavior here.
160             Log.i("FragmentComplexList", "Item clicked: " + id);
161         }
162 
163         // These are the Contacts rows that we will retrieve.
164         static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
165             Contacts._ID,
166             Contacts.DISPLAY_NAME,
167             Contacts.CONTACT_STATUS,
168             Contacts.CONTACT_PRESENCE,
169             Contacts.PHOTO_ID,
170             Contacts.LOOKUP_KEY,
171         };
172 
onCreateLoader(int id, Bundle args)173         public Loader<Cursor> onCreateLoader(int id, Bundle args) {
174             // This is called when a new Loader needs to be created.  This
175             // sample only has one Loader, so we don't care about the ID.
176             // First, pick the base URI to use depending on whether we are
177             // currently filtering.
178             Uri baseUri;
179             if (mCurFilter != null) {
180                 baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
181                         Uri.encode(mCurFilter));
182             } else {
183                 baseUri = Contacts.CONTENT_URI;
184             }
185 
186             // Now create and return a CursorLoader that will take care of
187             // creating a Cursor for the data being displayed.
188             String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
189                     + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
190                     + Contacts.DISPLAY_NAME + " != '' ))";
191             return new CursorLoader(getActivity(), baseUri,
192                     CONTACTS_SUMMARY_PROJECTION, select, null,
193                     Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
194         }
195 
onLoadFinished(Loader<Cursor> loader, Cursor data)196         public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
197             // Swap the new cursor in.  (The framework will take care of closing the
198             // old cursor once we return.)
199             mAdapter.swapCursor(data);
200 
201             // The list should now be shown.
202             if (isResumed()) {
203                 setListShown(true);
204             } else {
205                 setListShownNoAnimation(true);
206             }
207         }
208 
onLoaderReset(Loader<Cursor> loader)209         public void onLoaderReset(Loader<Cursor> loader) {
210             // This is called when the last Cursor provided to onLoadFinished()
211             // above is about to be closed.  We need to make sure we are no
212             // longer using it.
213             mAdapter.swapCursor(null);
214         }
215     }
216 //END_INCLUDE(fragment_cursor)
217 }
218