NetworkOnMainThreadException при использовании AsyncTask для анализа онлайн-файла XML в Android Studio - PullRequest
0 голосов
/ 19 мая 2018

Я создаю конвертер валют, который использует следующие API-интерфейсы XML для получения курсов: http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

Однако я получаю ошибку NetworkOnMainThreadException в функции.

Вот моя функция XMLPath, котораядолжен сканировать API и сохранить все тарифы оттуда в ArrayList:

    private static final String CURRENCY = "currency";
private static final String RATE = "rate";
private static final String CUBE_NODE = "//Cube/Cube/Cube";

public class XMLPath extends AsyncTask<URL, Void, List<Currency_Rate>> {

    @Override
    protected List<Currency_Rate> doInBackground(URL... urls){

        List<Currency_Rate> currRateList = new ArrayList<>();

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;

        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = null;
        String target_url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";

        try{
            URL xmlurl = new URL(target_url);
            InputStream xml = xmlurl.openStream();
            document = builder.parse(xml);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            String xPathString = CUBE_NODE;

            XPathExpression expression = xpath.compile(xPathString);

            NodeList nodel = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

            for (int i = 0; i < nodel.getLength(); i++){

                Node node = nodel.item(i);
                NamedNodeMap attr = node.getAttributes();

                if(attr.getLength() > 0) {
                    Node currencyAttr = attr.getNamedItem(CURRENCY);

                    if(currencyAttr != null){
                        String currency_text = currencyAttr.getNodeValue();
                        String rate_text = attr.getNamedItem(RATE).getNodeValue();
                        currRateList.add(new Currency_Rate(rate_text));

                        Log.i("Rate", rate_text.toString());
                    }
                }
            }
        } catch (SAXException | XPathExpressionException | IOException e) {
            e.printStackTrace();
        }

        for (Currency_Rate currency_rate : currRateList){

            System.out.println(currency_rate);
        }


        return currRateList;
    }

    @Override
    protected void onPostExecute(List<Currency_Rate> currRateList)
    {
        super.onPostExecute(currRateList);
    }

}

Я получаю сообщение об ошибке в следующей строке:

document = builder.parse(xml);

У меня включен доступ к Интернету вфайл манифеста:

<uses-permission android:name="android.permission.INTERNET" />

РЕДАКТИРОВАТЬ

В OnCreate () MainActivity приложения я вызываю класс:

    XMLPath xmlpath = new XMLPath();
    xmlpath.doInBackground();

Очень потерян с решениемк этому, поэтому любая помощь будет оценена!Спасибо

1 Ответ

0 голосов
/ 19 мая 2018
XMLPath xmlpath = new XMLPath();
xmlpath.doInBackground();

Вы не должны звонить doInBackground() напрямую.Вместо этого вызовите один из execute() методов, чтобы запустить асинхронную задачу в фоновом потоке.

...