LoaderRetainedSupport.java revision 6a8875b9abd9914c20d28ccd8eb483da4ff9e4a5
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
17package com.example.android.supportv4.app;
18
19import android.support.v4.app.FragmentActivity;
20import android.support.v4.app.FragmentManager;
21import android.support.v4.app.ListFragment;
22import android.support.v4.app.LoaderManager;
23import android.support.v4.content.CursorLoader;
24import android.support.v4.content.Loader;
25import android.support.v4.view.MenuItemCompat;
26import android.support.v4.widget.SearchViewCompat;
27import android.support.v4.widget.SearchViewCompat.OnQueryTextListenerCompat;
28import android.support.v4.widget.SimpleCursorAdapter;
29
30import android.database.Cursor;
31import android.net.Uri;
32import android.os.Bundle;
33import android.provider.BaseColumns;
34import android.provider.Contacts.People;
35import android.text.TextUtils;
36import android.util.Log;
37import android.view.Menu;
38import android.view.MenuInflater;
39import android.view.MenuItem;
40import android.view.View;
41import android.widget.ListView;
42
43/**
44 * Demonstration of the use of a CursorLoader to load and display contacts
45 * data in a fragment.
46 */
47@SuppressWarnings("all")
48public class LoaderRetainedSupport extends FragmentActivity {
49
50    @Override
51    protected void onCreate(Bundle savedInstanceState) {
52        super.onCreate(savedInstanceState);
53
54        FragmentManager fm = getSupportFragmentManager();
55
56        // Create the list fragment and add it as our sole content.
57        if (fm.findFragmentById(android.R.id.content) == null) {
58            CursorLoaderListFragment list = new CursorLoaderListFragment();
59            fm.beginTransaction().add(android.R.id.content, list).commit();
60        }
61    }
62
63//BEGIN_INCLUDE(fragment_cursor)
64    public static class CursorLoaderListFragment extends ListFragment
65            implements LoaderManager.LoaderCallbacks<Cursor> {
66
67        // This is the Adapter being used to display the list's data.
68        SimpleCursorAdapter mAdapter;
69
70        // If non-null, this is the current filter the user has provided.
71        String mCurFilter;
72
73        @Override public void onActivityCreated(Bundle savedInstanceState) {
74            super.onActivityCreated(savedInstanceState);
75
76            // In this sample we are going to use a retained fragment.
77            setRetainInstance(true);
78
79            // Give some text to display if there is no data.  In a real
80            // application this would come from a resource.
81            setEmptyText("No phone numbers");
82
83            // We have a menu item to show in action bar.
84            setHasOptionsMenu(true);
85
86            // Create an empty adapter we will use to display the loaded data.
87            mAdapter = new SimpleCursorAdapter(getActivity(),
88                    android.R.layout.simple_list_item_1, null,
89                    new String[] { People.DISPLAY_NAME },
90                    new int[] { android.R.id.text1}, 0);
91            setListAdapter(mAdapter);
92
93            // Start out with a progress indicator.
94            setListShown(false);
95
96            // Prepare the loader.  Either re-connect with an existing one,
97            // or start a new one.
98            getLoaderManager().initLoader(0, null, this);
99        }
100
101        @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
102            // Place an action bar item for searching.
103            MenuItem item = menu.add("Search");
104            item.setIcon(android.R.drawable.ic_menu_search);
105            MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_ALWAYS
106                    | MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
107            View searchView = SearchViewCompat.newSearchView(getActivity());
108            if (searchView != null) {
109                SearchViewCompat.setOnQueryTextListener(searchView,
110                        new OnQueryTextListenerCompat() {
111                    @Override
112                    public boolean onQueryTextChange(String newText) {
113                        // Called when the action bar search text has changed.  Update
114                        // the search filter, and restart the loader to do a new query
115                        // with this filter.
116                        String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
117                        // Don't do anything if the filter hasn't actually changed.
118                        // Prevents restarting the loader when restoring state.
119                        if (mCurFilter == null && newFilter == null) {
120                            return true;
121                        }
122                        if (mCurFilter != null && mCurFilter.equals(newFilter)) {
123                            return true;
124                        }
125                        mCurFilter = newFilter;
126                        getLoaderManager().restartLoader(0, null, CursorLoaderListFragment.this);
127                        return true;
128                    }
129                });
130                MenuItemCompat.setActionView(item, searchView);
131            }
132        }
133
134        @Override public void onListItemClick(ListView l, View v, int position, long id) {
135            // Insert desired behavior here.
136            Log.i("FragmentComplexList", "Item clicked: " + id);
137        }
138
139        // These are the Contacts rows that we will retrieve.
140        static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
141            People._ID,
142            People.DISPLAY_NAME,
143        };
144
145        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
146            // This is called when a new Loader needs to be created.  This
147            // sample only has one Loader, so we don't care about the ID.
148            // First, pick the base URI to use depending on whether we are
149            // currently filtering.
150            Uri baseUri;
151            if (mCurFilter != null) {
152                baseUri = Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(mCurFilter));
153            } else {
154                baseUri = People.CONTENT_URI;
155            }
156
157            // Now create and return a CursorLoader that will take care of
158            // creating a Cursor for the data being displayed.
159            String select = "((" + People.DISPLAY_NAME + " NOTNULL) AND ("
160                    + People.DISPLAY_NAME + " != '' ))";
161            return new CursorLoader(getActivity(), baseUri,
162                    CONTACTS_SUMMARY_PROJECTION, select, null,
163                    People.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