Reputation: 155
I am looking for a possibility to get an element only if it exists. Otherwise I get an error, because it does not exists.
Following case which I have:
What I have:
Element e = doc.getElementsByClass("table table-striped table-hover nofooter-").first();
Element tbody = e.select("tbody").first();
int j = 0;
while(tbody != null){
Element tr = tbody.select("tr").get(j); //Look for the next "tr" --> HERE: error, because there is no more "tr", if string "A" not found in all existing "tr"s.
if(tr != null){
if(string == "A"){
//Do something
}
j = j+1; //Increment for looking for the next "tr"
}
}
So I need a construct to check, if a "next" "tr" element exists.
Upvotes: 8
Views: 8842
Reputation: 8746
The problem is that you are chaining multiple methods together when you do:
tbody.select("tr").get(j);
If the first part of the statement, tbody.select("tr")
, returns nothing, you will get an error when you try to call get(j)
, since you can't call methods on an empty object.
Instead, break your methods up on to separate lines.
First do tbody.select("tr")
and save that result into a separate elements
variable. Then, add a check to see if the elements variable is empty. You can do that by either doing !elements.isEmpty()
or elements.size() > 0
. Once you determine that the variable is not empty, you can call .get(j)
method on the variable and set the Element tr
value.
The resulting code will look something like the following:
while(tbody != null){
Elements elements = tbody.select("tr");
if(!elements.isEmpty()){
Element tr = temp.get(j);
if(tr != null){
if(string == "A"){
//Do something
}
j = j + 1; //Increment for looking for the next "tr"
}
}
}
Upvotes: 11