Разбор XML в TextView: android - PullRequest
       27

Разбор XML в TextView: android

0 голосов
/ 26 марта 2020

Я работаю над приложением, которое отображает список книг в android. Где я получаю файл XML с сервера и анализирую содержимое в соответствующих TextViews.

мой XML файл:

<bib>
<book year="1988">
    <title>Book Title</title>
    <author>
        <last>Jones</last>
        <first>Ryan</first>
    </author>
</book>

<book year="2001">
    <title>Book Title 2</title>
    <author>
        <last>Ryans</last>
        <first>Jack</first>
    </author>
</book>

Я использую ViewModel для анализа XML в моем приложении с использованием NodeList.

ViewModel. java:

try {

                String bFeed = getApplication().getString(R.string.feed);

                URL url = new URL(bFeed);
                URLConnection connection = url.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();

                if (responseCode == HttpURLConnection.HTTP_OK) {

                    InputStream in = httpConnection.getInputStream();
                    DocumentBuilderFactory dbf =
                            DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();

                    // Parse the book feed.
                    Document dom = db.parse(in);
                    // Returns the root element.
                    Element docEle = dom.getDocumentElement();
                    books.clear();

                    NodeList nl = docEle.getElementsByTagName("book");
                    if (nl != null && nl.getLength() > 0) {

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

                            if (isCancelled()) {
                                return books;
                            }
                            Element bookElement = (Element) nl.item(i);
                            Element title = (Element) bookElement
                                    .getElementsByTagName("title").item(0);
                            Element author = (Element) bookElement
                                    .getElementsByTagName("author").item(0);

                            String bookTitle = title.getFirstChild().getNodeValue();
                            String bookYear = ((Element) bookElement).getAttribute("year");
                            // Error occurs
                            String bookAuthor = author.getFirstChild().getNodeValue();

                            final Book bookObject = new Book(bookTitle, bookYear, bookAuthor);
                            books.add(bookObject);

                        }
                    }
                }
                httpConnection.disconnect();
            } catch (MalformedURLException e) {
                Log.e(TAG, "MalformedURLException", e);
            } catch (IOException e) {
                Log.e(TAG, "IOException", e);
            } catch (ParserConfigurationException e) {
                Log.e(TAG, "Parser Configuration Exception", e);
            } catch (SAXException e) {
                Log.e(TAG, "SAX Exception", e);
            }

            return books;
        }

Я получаю эту ошибку во время выполнения:

Причина: java .lang.NullPointerException: Попытка вызвать метод интерфейса 'org.w3 c .dom.Node org.w3 c .dom.Element.getFirstChild () 'для нулевой ссылки на объект

book. java:

public class Book {
private String year;
private String title;
private String author;


public String getYear() { return year; }

public String getTitle() {
    return title;
}

public String getAuthor() { return author; }

public Book(String year, String title, String author) {

    this.year = year;
    this.title = title;
    this.author = author;

}

Мне бы хотелось чтобы можно было получить дочерние узлы автора. Буду признателен, если кто-нибудь может дать какой-нибудь совет относительно того, что я делаю неправильно?

Спасибо

1 Ответ

0 голосов
/ 26 марта 2020

Ошибка, которую вы получаете, очень ясна:

java .lang.NullPointerException: попытка вызвать метод интерфейса 'org.w3 c .dom.Node org.w3 c .dom.Element.getFirstChild () 'для ссылки на нулевой объект

То есть вы пытаетесь вызвать getFirstChildMethod для объекта, который является нулевым.

Я бы проверил, что в строке ниже:

String bookTitle = title.getFirstChild().getNodeValue();

заголовок действительно имеет значение.

Не видя фактического XML, который вы анализируете, эти строки являются виновником:

Element bookElement = (Element) nl.item(i);
Element title = (Element) bookElement.getElementsByTagName("title").item(0);
...