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