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

(gtxtreme123) #1
Searching Flickr

Rename fetchItems() to downloadGalleryItems(String url) to reflect its new, more general
purpose. It no longer needs to be public, either, so change its visibility to private.


Listing 27.2  Refactoring Flickr code (FlickrFetchr.java)


public class FlickrFetchr {
...
public List fetchItems() {
private List downloadGalleryItems(String url) {


List items = new ArrayList<>();


try {
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
parseItems(items, jsonBody);
} 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 new downloadGalleryItems(String) method takes a URL as input, so there is no need to build
the URL inside. Instead, add a new method to build the URL based on method and query values.


Listing 27.3  Adding helper method to build URL (FlickrFetchr.java)


public class FlickrFetchr {
...
private List downloadGalleryItems(String url) {
...
}


private String buildUrl(String method, String query) {
Uri.Builder uriBuilder = ENDPOINT.buildUpon()
.appendQueryParameter("method", method);


if (method.equals(SEARCH_METHOD)) {
uriBuilder.appendQueryParameter("text", query);
}


return uriBuilder.build().toString();
}


private void parseItems(List items, JSONObject jsonBody)
throws IOException, JSONException {
...
}
}


The buildUrl(...) method appends the necessary parameters, just as fetchItems() used to. But
it dynamically fills in the method parameter value. Additionally, it appends a value for the text
parameter only if the value specified for the method parameter is search.

Free download pdf