When you make Android applications, you can have to parse HTML data or HTML pages got from the Web. One of the most known solution to make that in Java is to use JSoup Library. Like said on the official website of JSoup : “It is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.”
JSoup can be used in Android applications and we’re going to study how to parse an HTML Page on Android with JSoup. You can discover the tutorial in video on Youtube :
First, you need to add the JSoup dependency in your Gradle build file :
For our example, we are going to download the content of the SSaurel’s Blog and display all the links of the main page. To download the content of a website, JSoup offers the connect method and then a get method. This last method works synchronously. So, we should call these methods in a separated Thread. Our application will have just a simple layout with a Button to launch the download of the website and a TextView to display the links.
It will have the following form :
In the main Activity of the application, we are going to get instances of the Button and the TextView from our layout. Then, we set a click listener on the Button to start the download of the website when the user will click it.
In the getWebsite() method, we create a new Thread to download the content of the website. We use the connect() method of the Jsoup object to connect the application to the website, then we call the get() method to download the content. These calls return a Document object instance. We have to call the select() method of this instance with the query to get all the links of the content. This query returns an Elements instance and finally, we have just to iterate on the elements contained in this object to display the content of each link to the screen.
At the end of our separated Thread, we refresh the UI with the links got from the website. This refresh is embedded inside a runOnUiThread call because it’s forbidden to refresh the UI elements inside a separated thread.
The code of the MainActivity has the following form :
Last step is to run the application and to enjoy the final result with all the links of the SSaurel’s blog displayed on the screen :