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

(gtxtreme123) #1

Chapter 27  Search


The method is set to flickr.photos.search. A new parameter, text, is added and set to whatever
string you are searching for (“cat,” in this case).


While the search request URL differs from the one you used to request recent photos, the format of
the JSON returned remains the same. This is good news, because it means you can use the same JSON
parsing code you already wrote, regardless of whether you are searching or getting recent photos.


First, refactor some of your old FlickrFetchr code to reuse the parsing code across both scenarios.
Start by adding constants for the reusable pieces of the URL, as shown in Listing 27.1. Cut the URI-
building code from fetchItems and paste it as the value for ENDPOINT. However, make sure to only
include the shaded parts. The constant ENDPOINT should not contain the method query parameter, and
the build statement should not be converted to a string using toString().


Listing 27.1  Adding URL constants (FlickrFetchr.java)


public class FlickrFetchr {


private static final String TAG = "FlickrFetchr";


private static final String API_KEY = "yourApiKeyHere";
private static final String FETCH_RECENTS_METHOD = "flickr.photos.getRecent";
private static final String SEARCH_METHOD = "flickr.photos.search";
private static final Uri ENDPOINT = Uri
.parse("https://api.flickr.com/services/rest/")
.buildUpon()
.appendQueryParameter("api_key", API_KEY)
.appendQueryParameter("format", "json")
.appendQueryParameter("nojsoncallback", "1")
.appendQueryParameter("extras", "url_s")
.build();
...
public List fetchItems() {


List items = new ArrayList<>();


try {
String url = Uri.parse("https://api.flickr.com/services/rest/")
.buildUpon()
.appendQueryParameter("method", "flickr.photos.getRecent")
.appendQueryParameter("api_key", API_KEY)
.appendQueryParameter("format", "json")
.appendQueryParameter("nojsoncallback", "1")
.appendQueryParameter("extras", "url_s")
.build().toString();
String jsonString = getUrlString(url);
...
} catch (IOException ioe) {
Log.e(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse JSON", je);
}


return items;
}
...
}


(The change you just made will result in an error in fetchItems(). You can ignore this error for now,
as you are about to rework fetchItems() into something new anyway.)

Free download pdf