LoaderCursorSupport.java revision 458543f38db49fdcb1764f007ded33820964c3fe
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
17package com.example.android.supportv4.app;
18
19import android.database.Cursor;
20import android.net.Uri;
21import android.os.Bundle;
22import android.provider.Contacts.People;
23import android.support.v4.app.FragmentActivity;
24import android.support.v4.app.FragmentManager;
25import android.support.v4.app.ListFragment;
26import android.support.v4.app.LoaderManager;
27import android.support.v4.content.CursorLoader;
28import android.support.v4.content.Loader;
29import android.support.v4.widget.SimpleCursorAdapter;
30import android.text.TextUtils;
31import android.util.Log;
32import android.view.Menu;
33import android.view.MenuInflater;
34import android.view.MenuItem;
35import android.view.View;
36import android.widget.ListView;
37import android.widget.SearchView;
38
39/**
40 * Demonstration of the use of a CursorLoader to load and display contacts
41 * data in a fragment.
42 */
43@SuppressWarnings("all")
44public class LoaderCursorSupport extends FragmentActivity {
45
46    @Override
47    protected void onCreate(Bundle savedInstanceState) {
48        super.onCreate(savedInstanceState);
49
50        FragmentManager fm = getSupportFragmentManager();
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 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_1, null,
82                    new String[] { People.DISPLAY_NAME },
83                    new int[] { android.R.id.text1}, 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_ALWAYS
99                    | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
100            final SearchView searchView = new SearchView(getActivity());
101            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
102                @Override
103                public boolean onQueryTextChange(String newText) {
104                    // Called when the action bar search text has changed.  Update
105                    // the search filter, and restart the loader to do a new query
106                    // with this filter.
107                    String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
108                    // Don't do anything if the filter hasn't actually changed.
109                    // Prevents restarting the loader when restoring state.
110                    if (mCurFilter == null && newFilter == null) {
111                        return true;
112                    }
113                    if (mCurFilter != null && mCurFilter.equals(newFilter)) {
114                        return true;
115                    }
116                    mCurFilter = newFilter;
117                    getLoaderManager().restartLoader(0, null, CursorLoaderListFragment.this);
118                    return true;
119                }
120
121                @Override
122                public boolean onQueryTextSubmit(String s) {
123                    return false;
124                }
125            });
126            searchView.setOnCloseListener(new SearchView.OnCloseListener() {
127                @Override
128                public boolean onClose() {
129                    if (!TextUtils.isEmpty(searchView.getQuery())) {
130                        searchView.setQuery(null, true);
131                    }
132                    return true;
133                }
134            });
135            item.setActionView(searchView);
136        }
137
138        @Override public void onListItemClick(ListView l, View v, int position, long id) {
139            // Insert desired behavior here.
140            Log.i("FragmentComplexList", "Item clicked: " + id);
141        }
142
143        // These are the Contacts rows that we will retrieve.
144        static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
145            People._ID,
146            People.DISPLAY_NAME,
147        };
148
149        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
150            // This is called when a new Loader needs to be created.  This
151            // sample only has one Loader, so we don't care about the ID.
152            // First, pick the base URI to use depending on whether we are
153            // currently filtering.
154            Uri baseUri;
155            if (mCurFilter != null) {
156                baseUri = Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(mCurFilter));
157            } else {
158                baseUri = People.CONTENT_URI;
159            }
160
161            // Now create and return a CursorLoader that will take care of
162            // creating a Cursor for the data being displayed.
163            String select = "((" + People.DISPLAY_NAME + " NOTNULL) AND ("
164                    + People.DISPLAY_NAME + " != '' ))";
165            return new CursorLoader(getActivity(), baseUri,
166                    CONTACTS_SUMMARY_PROJECTION, select, null,
167                    People.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
168        }
169
170        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
171            // Swap the new cursor in.  (The framework will take care of closing the
172            // old cursor once we return.)
173            mAdapter.swapCursor(data);
174
175            // The list should now be shown.
176            if (isResumed()) {
177                setListShown(true);
178            } else {
179                setListShownNoAnimation(true);
180            }
181        }
182
183        public void onLoaderReset(Loader<Cursor> loader) {
184            // This is called when the last Cursor provided to onLoadFinished()
185            // above is about to be closed.  We need to make sure we are no
186            // longer using it.
187            mAdapter.swapCursor(null);
188        }
189    }
190//END_INCLUDE(fragment_cursor)
191}
192