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