LoaderRetainedSupport.java revision 458543f38db49fdcb1764f007ded33820964c3fe
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.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 LoaderRetainedSupport 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            // 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_1, null,
85                    new String[] { People.DISPLAY_NAME },
86                    new int[] { android.R.id.text1}, 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_ALWAYS
102                    | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
103            SearchView searchView = new SearchView(getActivity());
104            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
105                @Override
106                public boolean onQueryTextChange(String newText) {
107                    // Called when the action bar search text has changed.  Update
108                    // the search filter, and restart the loader to do a new query
109                    // with this filter.
110                    String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
111                    // Don't do anything if the filter hasn't actually changed.
112                    // Prevents restarting the loader when restoring state.
113                    if (mCurFilter == null && newFilter == null) {
114                        return true;
115                    }
116                    if (mCurFilter != null && mCurFilter.equals(newFilter)) {
117                        return true;
118                    }
119                    mCurFilter = newFilter;
120                    getLoaderManager().restartLoader(0, null, CursorLoaderListFragment.this);
121                    return true;
122                }
123
124                @Override
125                public boolean onQueryTextSubmit(String s) {
126                    return false;
127                }
128            });
129            item.setActionView(searchView);
130        }
131
132        @Override public void onListItemClick(ListView l, View v, int position, long id) {
133            // Insert desired behavior here.
134            Log.i("FragmentComplexList", "Item clicked: " + id);
135        }
136
137        // These are the Contacts rows that we will retrieve.
138        static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
139            People._ID,
140            People.DISPLAY_NAME,
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(People.CONTENT_FILTER_URI, Uri.encode(mCurFilter));
151            } else {
152                baseUri = People.CONTENT_URI;
153            }
154
155            // Now create and return a CursorLoader that will take care of
156            // creating a Cursor for the data being displayed.
157            String select = "((" + People.DISPLAY_NAME + " NOTNULL) AND ("
158                    + People.DISPLAY_NAME + " != '' ))";
159            return new CursorLoader(getActivity(), baseUri,
160                    CONTACTS_SUMMARY_PROJECTION, select, null,
161                    People.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
162        }
163
164        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
165            // Swap the new cursor in.  (The framework will take care of closing the
166            // old cursor once we return.)
167            mAdapter.swapCursor(data);
168
169            // The list should now be shown.
170            if (isResumed()) {
171                setListShown(true);
172            } else {
173                setListShownNoAnimation(true);
174            }
175        }
176
177        public void onLoaderReset(Loader<Cursor> loader) {
178            // This is called when the last Cursor provided to onLoadFinished()
179            // above is about to be closed.  We need to make sure we are no
180            // longer using it.
181            mAdapter.swapCursor(null);
182        }
183    }
184//END_INCLUDE(fragment_cursor)
185}
186