Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Responding to SearchView user interactions

The onQueryTextSubmit(String) callback is executed when the user submits a query. The query
the user submitted is passed as input. Returning true signifies to the system that the search request
has been handled. This callback is where you will launch a FetchItemsTask to query for new results.
(Right now FetchItemsTask still has a hardcoded query. You will refactor FetchItemsTask in a bit so
that it uses a submitted query if there is one.)


updateItems() does not seem terribly useful just yet. Later on you will have several places where you
need to execute FetchItemsTask. The updateItems() method is a wrapper for doing just that.


As a last bit of cleanup, replace the line that creates and executes a FetchItemsTask with a call to
updateItems() in the onCreate(...) method.


Listing 27.10  Cleaning up onCreate(...) (PhotoGalleryFragment.java)


public class PhotoGalleryFragment extends Fragment {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
new FetchItemsTask().execute();
updateItems();
...
Log.i(TAG, "Background thread started");
}
...
}


Run your app and submit a query. The search results will still be based on the hardcoded query in
Listing 27.5, but you should see the images reload. You should also see log statements reflecting the
fact that your SearchView.OnQueryTextListener callback methods have been executed.


Note that if you use the hardware keyboard (e.g., from your laptop) to submit your search query on an
emulator, you will see the search executed two times, one after the other. It will look like the images
start to load, then load all over again. This is because there is a small bug in SearchView. You can
ignore this behavior because it is simply a side effect of using the emulator and will not affect your app
when it runs on a real Android device.

Free download pdf