I know that I have to use ASyncTasks in order to make JSoup work for android, but all examples online illustrate that just by using random jsoup methods in the MainActivity
.
I want to create a HTMLParser
class which will contains a function for each element I want to parse but I can't seem to make it work.
My HTMLParser
:
public class HTMLParser extends AsyncTask<Void, Void, Void> {
private Document doc;
@Override
protected Void doInBackground(Void... voids) {
try {
doc = Jsoup.connect("https://www.bodybuilding.com/exercises").get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public ArrayList<String> findMuscleGroups(){
ArrayList<String> muscleGroups = new ArrayList<>();
Elements section = doc.select("a");
if (section != null) {
for (Element exercise : section) {
if (exercise.hasText() && !muscleGroups.contains(exercise.text()) &&
exercise.attr("href").contains("exercises/muscle")) {
muscleGroups.add(exercise.text());
}
}
}
return muscleGroups;
}
}
In my MainActivity
I want to be able to create a HTMLParser
object and be able to use something like ArrayList = htmlParser.findMuscleGroups()
My MainActivity
:
HTMLParser parser = new HTMLParser();
new HTMLParser().execute();
for (String muscleGroup : parser.findMuscleGroups()){
textView.setText(muscleGroup + "\n");
}
Which won't work. I'm well aware that it isn't supposed to work and there is something I'm missing but I hope you guys can point me in the right direction.
Elements section = doc.select("a");
. In the other approach when I would try to use the getter on the class variable it would directly give me an empty array (default initialization) and won't call the method to populate it in the onPostExecute(). But that's ok because it was a bad idea to begin with Also, the code itself in thefindMuscleGroups
function is fine, I've tested it in an empty project