How to receive external data via XML

4

I'm creating an android app and I need it to receive and display on-screen information from the tide board of the site below:

link

    
asked by anonymous 15.08.2016 / 16:09

1 answer

5

Follows:

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

          public class LoadMares extends AsyncTask<String, Void, City>{
                /**
                 * Transforma uma String em um Document para navegar pelos nos
                 */
                public Document getDomElement(String xml) {
                    Document doc = null;
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        InputSource is = new InputSource();
                        is.setCharacterStream(new StringReader(xml));
                        doc = db.parse(is);
                    } catch (ParserConfigurationException e) {
                        Log.e("Error: ", e.getMessage());
                        return null;
                    } catch (SAXException e) {
                        Log.e("Error: ", e.getMessage());
                        return null;
                    } catch (IOException e) {
                        Log.e("Error: ", e.getMessage());
                        return null;
                    }
                    return doc;
                }


                /**
                 * Retorna a String refrente ao valor
                 */
                public String getValue(Element item, String str) {
                    NodeList n = item.getElementsByTagName(str);
                    return this.getElementValue(n.item(0));
                }


                public final String getElementValue(Node elem) {
                    Node child;
                    if (elem != null) {
                        if (elem.hasChildNodes()) {
                            for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
                                if (child.getNodeType() == Node.TEXT_NODE) {
                                    return child.getNodeValue();
                                }
                            }
                        }
                    }
                    return "";
                }

                @Override
                protected City doInBackground(String... params) {
                    String idCIDADE = params[0];

                    City city = new City();
                    try {
                        // Exemplo de como vamos montar a url, o idCIDADE, podera ser passado cia parametro
                        final URL url = new URL(String.format("http://servicos.cptec.inpe.br/XML/cidade/%s/todos/tempos/ondas.xml", idCIDADE));
                        //Conexão...
                        final HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection());
                        final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO-8859-1"));
                        try {

                            final StringBuffer buffer = new StringBuffer("");
                            String line = "";
                            while ((line = reader.readLine()) != null) {
                                buffer.append(line);
                            }

                            final Document document = getDomElement(buffer.toString());

                            final NodeList nodeList = document.getElementsByTagName("cidade");
                            Element item = Element.class.cast(nodeList.item(0));
                            city.nome = getValue(item, "nome");
                            city.uf =  getValue(item, "uf");

                            // vamos pegar as previsões...
                            NodeList nodePrevisoes = document.getElementsByTagName("previsao");
                            List<Forecast> forecasts = new ArrayList<>();
                            for (int i = 0; i < nodePrevisoes.getLength(); i++) {
                                Element e = Element.class.cast(nodePrevisoes.item(i));
                                Forecast forecast = new Forecast();
                                forecast.dia = getValue(e, "dia");
                                forecast.agitacao = getValue(e, "agitacao");
                                forecast.altura = getValue(e, "altura");
                                forecast.direcao = getValue(e, "direcao");
                                forecast.vento = getValue(e, "vento");
                                forecast.vento_dir = getValue(e, "vento_dir");
                                forecasts.add(forecast);
                            }
                            city.forecasts = forecasts;
                        }finally {
                            reader.close();
                        }
                    } catch (final Exception e) {
                        e.printStackTrace();
                    }
                    return city;
                }

                @Override
                protected void onPostExecute(City city) {
                    super.onPostExecute(city);

                    for(final Forecast forecast : city.forecasts){
                        Log.d("Forecast: ", forecast.toString());
                    }
                }
            }

        // Classes auxiliares para guardar as informações

            class City{
                public String nome;
                public String uf;
                public List<Forecast> forecasts;
            }
            class Forecast{
                public String dia;
                public String agitacao;
                public String altura;
                public String direcao;
                public String vento;
                public String vento_dir;

                @Override
                public String toString() {
                    return "Forecast{" +
                            "dia='" + dia + '\'' +
                            ", agitacao='" + agitacao + '\'' +
                            ", altura='" + altura + '\'' +
                            ", direcao='" + direcao + '\'' +
                            ", vento='" + vento + '\'' +
                            ", vento_dir='" + vento_dir + '\'' +
                            '}';
                }
            }

Call:

new LoadMares().execute("241");
    
16.08.2016 / 18:11