I am parsing some URL links with the following..
Document jsDoc2 = null;
try {
jsDoc2 = Jsoup.connect(url).get();
Elements thumbs = jsDoc2.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
for(String thumb : thumbLinks) {
url0 = thumbLinks.get(0);
url1 = thumbLinks.get(1);
url2 = thumbLinks.get(2);
Log.e("URL0", url0);
Log.e("URL1", url1);
Log.e("URL2", url2);
After testing the code with multiple sources. ive ran across a problem.
09-19 20:59:56.710: ERROR/AndroidRuntime(7793): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
09-19 20:59:56.710: ERROR/AndroidRuntime(7793): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
09-19 20:59:56.710: ERROR/AndroidRuntime(7793): at java.util.ArrayList.get(ArrayList.java:308)
Sometimes there arent three links availible and of cource when i ask to get the index of 2 and it doesnt exist it FC’s.
How can i code defensively or create a better way to implement this. The uncertainty of not knowing the exact amount of urls it will parse and load into the list
EDIT:
My COde now
for(int i = 0; i< thumbLinks.size(); i++) {
Log.e("URL" + i, thumbLinks.get(i));
url0 = thumbLinks.get(i);
url1 = thumbLinks.get(i);
//Fix index out of bounds exception
url2 = thumbLinks.get(i);
}
Think this might work better for your loop structure
You could also just shorten this to something like:
This second option reduces the operational time by reducing the looping structures and providing the same result. You will not get index out of bound errors with either of these because it will only add URLs if there are thumbs in your list.
The reason your code is failing is because you’re explicitly trying to call indexes and essentially ignoring the loop structure all together. The reason to use a loop is so you don’t have explicitly get objects from the array and chance out of bounds exceptions.