Populating a Spinner with list of Java classes from online

Viewed 204
1 Answers

You have a few choices here.

Proper API

The best way would be to find a proper programmatic/API way to query the data. (For example a SOAP or Restful web service).

Since it seems likely in this case that that's not possible then you have two choices:

Local List

Build the list yourself and store it locally. For example copy the contents of the web page into a text page, csv file, database table, etc and then query it.

This has the advantage of being simple, robust and reliable; however it will not automatically update if any changes are made.

Parse the Web Page

Essentially you need to load the web page using a HTTPURLConnection, then parse the returned body. For each <a> tag inside the <ul> you would extract any data you need (for example the contents of the tag) and build that into a list.

The list can then be displayed as usual.

The problem with this approach is you are relying on that external web page, which you have no control over, remaining in the same place and containing the same format of contents. It could change at any point and would immediately break your program. Even worse it could change subtly and you would still parse it and get some results but not everything and you may not even realize for a while that your program is working with bad data.

protected <T> T getFromURLAndParse(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    try {
        connection.setRequestMethod("GET");

        if (connection.getResponseCode() == 200) {
            // Parse String from connection.getInputStream()
        } else {
            // Handle failure
        }
    } finally {
        connection.disconnect();
    }
}

For the actual parsing do "view source" on the web page and you can see the layout. How the web page is at the moment I would scan for the first <ul> tag and then inside that scan every <a> tag and read out the contents until you find a </ul> tag. As already mentioned though this is very fragile - if the web page changes your program will fail.

Related