When using 12 in iteration (inside for) it output correctly, when assigning 13 to iterator (inside for) throws IndexOutOfBoundsException
on line
imageUrl[i]=images.select("img").get(i).absUrl("data-original");`.
Note: class lazy in hasClass("lazy") has 12 elements:
Elements headlines = document.select("div.newscat a[href] h3");
Elements images=document.select("div.newscat").select("a[href]");
int lengthHeadline = headlines.size(); // outputs 13
String[] newsHeadline=new String[lengthHeadline];
String[] imageUrl=new String[lengthHeadline]
for(int i=0; i<12; i++){
if (images.get(i).children().hasClass("lazy")){
imageUrl[i] = images.select("img").get(i).absUrl("data-original");
}else{
imageUrl[i] = "http://something.com/8046.png";
}
System.out.println(imageUrl[i]);
}
EDIT:
HTML code
Here I have let say n number of .newscat classes and each of them contains picture and headlines, but in some cases they hold no image but headline only, so instead of blank-display I want to display any other image. So my image array should math that of headline.
The View that I want to be displayed (something like that).
答案 0 :(得分:2)
将13分配给迭代器(inside for)时抛出IndexOutOfBoundsException行
imageUrl[i] = images.select("img").get(i).absUrl("data-original");
不检查Element
返回的images.select("img")
列表大小。
而是试试这个:
if (images.get(i).children().hasClass("lazy")) {
Elements imgs = images.select("img");
if (imgs.size() < i) {
imageUrl[i] = imgs.get(i).absUrl("data-original");
} else {
// Handle the edge case here...
}
} else {
imageUrl[i] = "http://something.com/8046.png";
}