Search code examples
arraysprocessingflickr

arrayoutofboundsexception when using flickr api


i have a piece of code thats makes a image search on flickr and returns the URL of the first image with that name. certain words i search on flickr doesn't have any matching images so because there are no images to get i get an ArrayOutOfBoundsException [0]. is there a way that i can make the program skip that particular words and keep on searching with next words?

this is my code so far:

PImage[] images;
int imageIndex;
XML xml; 
String tag = "rutte";
String tag_mode = "all";
String words[];

void setup() {
   size(50, 50);
   String lines[] = loadStrings("text.txt");
   words = split(lines[0], " ");


for (int k = 0; k<words.length; k++) {  
String query = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY API KEY&tags="+ words[k] + "&sort=relevance&tag_mode="+ tag_mode +"format=rest";
xml = loadXML(query);
XML[] children = xml.getChildren("photos");
if(children.length > 0){
XML[] childPhoto = children[0].getChildren("photo");


  for (int i = 0; i < 1; i++) {
     String id = childPhoto[i].getString("id");       // this line generates the error :(
     String title = childPhoto[i].getString("title");
     String user = childPhoto[i].getString("owner");
     String url = "https://www.flickr.com/photos/"+user+"/"+id;
     println(url);
     println("=====================");
  }
}
}

textAlign(CENTER, CENTER);
smooth();
}

void draw() {
}

Solution

  • Just use the length field of your array. Something like this:

    XML[] children = xml.getChildren("photos");
    if(children.length > 0){
       XML[] childPhoto = children[0].getChildren("photo");
    
       if(childPhoto.length > 0){
          String id = childPhoto[0].getString("id");  
          //rest of your code
       }
    

    You can find more info in the Processing reference.

    In fact, you're already doing this with your words array!