Flickr api, random image goodness


SDK Version: 
M3

Lately we have been doing all kinds of demo projects, and tests, where we did not want to use constant data to present our products. Having a demo of your application is only nice, if it has relevant data in it. It could be top class technology, but if it is using the same image 20 times in a list, well that does not look very good.
Getting 20 relevant images on a subject takes up a lot of time, even with search engines and royalty free photo sites.Luckily most search able sites have free apis, here is a little snippet for flickr's services.
flickr

The Flickr api has a lot of useful methods, but I only needed one, which is search. I choose the json response, because that's the easiest to work with. It has support for several other protocols/formats.
One problem that I encountered is, that the flickr api does not send a valid json response:

  1. jsonFlickrApi({"photos":{"page":1, "pages":73442, "perpage":1, "total":"73442", "photo":[{"id":"5138524515", "owner":"12766047@N06", "secret":"e000d9791e", "server":"4045", "farm":5, "title":"Gifts under $15 CAD", "ispublic":1, "isfriend":0, "isfamily":0}]}, "stat":"ok"})

As you can see, it has some junk at the beginning "jsonFlickrApi(" and at the end ")" which needs to be cut off.

  1. //you also need your own api key
  2. private static final String FLICKRAPIKEY = "http://www.flickr.com/services/api/keys/ INSERT YOUR OWN API KEY";
  3.  
  4. private String flickrApi(String searchPattern, int limit) throws IOException, JSONException {
  5.         URL url = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + searchPattern + "&api_key=" + FLICKRAPIKEY + "&per_page="+ limit + "&format=json");
  6.         URLConnection connection = url.openConnection();
  7.         String line;
  8.         StringBuilder builder = new StringBuilder();
  9.         BufferedReader reader = new BufferedReader(new InputStreamReader(
  10.                         connection.getInputStream()));
  11.         while ((line = reader.readLine()) != null) {
  12.                 builder.append(line);
  13.         }
  14.  
  15.         Log.d("not good",builder.toString());
  16.         //no, this is not yet a valid json response :)
  17.        
  18.         int start = builder.toString().indexOf("(") + 1;
  19.         int end = builder.toString().length() - 1;
  20.         String jSONString = builder.toString().substring( start, end);
  21.         //after cutting off the junk, its ok
  22.        
  23.         JSONObject jSONObject = new JSONObject(jSONString); //whole json object
  24.         JSONObject jSONObjectInner = jSONObject.getJSONObject("photos"); //inner Json object
  25.         JSONArray photoArray = jSONObjectInner.getJSONArray("photo"); // inner array of photos
  26.         JSONObject photo = photoArray.getJSONObject((int) (limit*Math.random())); //get one random photo from array
  27.  
  28.         return constructFlickrImgUrl(photo, size._t);
  29. }
  30.  
  31. // source: flickr.com/services/api/misc.urls.html
  32. enum size {
  33.         _s , _t ,_m
  34. };
  35.  
  36. //helper method, to construct the url from the json object. You can define the size of the image that you want, with the size parameter. Be aware that not all images on flickr are available in all sizes.
  37. private String constructFlickrImgUrl(JSONObject input, Enum size) throws JSONException {
  38.         String FARMID = input.getString("farm");
  39.         String SERVERID = input.getString("server");
  40.         String SECRET = input.getString("secret");
  41.         String ID = input.getString("id");
  42.  
  43.         StringBuilder sb = new StringBuilder();
  44.                
  45.         sb.append("http://farm");
  46.         sb.append(FARMID);
  47.         sb.append(".static.flickr.com/";);
  48.         sb.append(SERVERID);
  49.         sb.append("/");
  50.         sb.append(ID);
  51.         sb.append("_");
  52.         sb.append(SECRET);
  53.         sb.append(size.toString());                    
  54.         sb.append(".jpg");
  55.  
  56.         return sb.toString();
  57. }
  58.  
  59. /**
  60.  * Word randomizer for fun
  61.  * @param length
  62.  * @return
  63.  */
  64. private String randomizer(int length){
  65.         char i[] = new char[length];
  66.         for (int j = 0; j < length; j++) {
  67.                 i[j] =(char)((int)5*Math.random()+(int)'a');
  68.         }
  69.         return new String(i);
  70. }
  71.  
  72. //Usage:
  73. flickrApi(randomizer(3) , 1));