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.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 LoaderRetainedSupport 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            // In this sample we are going to use a retained fragment.
75            setRetainInstance(true);
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
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            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            item.setActionView(searchView);
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        @NonNull
146        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
147            // This is called when a new Loader needs to be created.  This
148            // sample only has one Loader, so we don't care about the ID.
149            // First, pick the base URI to use depending on whether we are
150            // currently filtering.
151            Uri baseUri;
152            if (mCurFilter != null) {
153                baseUri = Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(mCurFilter));
154            } else {
155                baseUri = People.CONTENT_URI;
156            }
157
158            // Now create and return a CursorLoader that will take care of
159            // creating a Cursor for the data being displayed.
160            String select = "((" + People.DISPLAY_NAME + " NOTNULL) AND ("
161                    + People.DISPLAY_NAME + " != '' ))";
162            return new CursorLoader(getActivity(), baseUri,
163                    CONTACTS_SUMMARY_PROJECTION, select, null,
164                    People.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
165        }
166
167        public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
168            // Swap the new cursor in.  (The framework will take care of closing the
169            // old cursor once we return.)
170            mAdapter.swapCursor(data);
171
172            // The list should now be shown.
173            if (isResumed()) {
174                setListShown(true);
175            } else {
176                setListShownNoAnimation(true);
177            }
178        }
179
180        public void onLoaderReset(@NonNull Loader<Cursor> loader) {
181            // This is called when the last Cursor provided to onLoadFinished()
182            // above is about to be closed.  We need to make sure we are no
183            // longer using it.
184            mAdapter.swapCursor(null);
185        }
186    }
187//END_INCLUDE(fragment_cursor)
188}
189