Now that you have a location fix, it is time to use it. Write an async task to find a GalleryItem near your location fix, download its associated image, and display it.
Put this code inside a new inner AsyncTask called SearchTask. Start by performing the search, selecting the first GalleryItem that comes up.
Listing 33.22 Writing SearchTask
(LocatrFragment.java
)
private void findImage() { ... LocationServices.FusedLocationApi .requestLocationUpdates(mClient, request, new LocationListener() { @Override public void onLocationChanged(Location location) { Log.i(TAG, "Got a fix: " + location); new SearchTask().execute(location); } }); } private boolean hasLocationPermission() { int result = ContextCompat .checkSelfPermission(getActivity(), LOCATION_PERMISSIONS[0]); return result == PackageManager.PERMISSION_GRANTED; } private class SearchTask extends AsyncTask<Location,Void,Void> { private GalleryItem mGalleryItem; @Override protected Void doInBackground(Location... params) { FlickrFetchr fetchr = new FlickrFetchr(); List<GalleryItem> items = fetchr.searchPhotos(params[0]); if (items.size() == 0) { return null; } mGalleryItem = items.get(0); return null; } }
Saving out the GalleryItem here accomplishes nothing for now. But it will save you a bit of typing in the next chapter.
Next, download that GalleryItem’s associated image data and decode it. Then display it on mImageView inside onPostExecute(Void).
Listing 33.23 Downloading and displaying image (LocatrFragment.java
)
private class SearchTask extends AsyncTask<Location,Void,Void> { private GalleryItem mGalleryItem; private Bitmap mBitmap; @Override protected Void doInBackground(Location... params) { ... mGalleryItem = items.get(0); try { byte[] bytes = fetchr.getUrlBytes(mGalleryItem.getUrl()); mBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } catch (IOException ioe) { Log.i(TAG, "Unable to download bitmap", ioe); } return null; } @Override protected void onPostExecute(Void result) { mImageView.setImageBitmap(mBitmap); } }
With that, you should be able to find a nearby image on Flickr (Figure 33.11). Fire up Locatr and press your location button.