返回空List会导致NullPointerException

时间:2016-09-23 17:15:26

标签: android arraylist


我试图创建一个简单的XML阅读器,我已经跟踪Android Developers网站上的Parsing XML DataList转换为Array

时出错
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

List已在ParseXML.java课程中实施,我不知道哪里错了。
我将代码留在下面,谢谢大家!

NewsFeedFragment.java

public void downloadWebpage(String link) {

    if (checkInternetConnection()) {
        // CALL AND GET LIST
        new DownloadFile(this).execute(link);
    }
    else {
        Toast.makeText(getActivity(), "Disconnected!", Toast.LENGTH_SHORT).show();
    }
}

public boolean checkInternetConnection() {
    ConnectivityManager connectivityManager =
            (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();

    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

@Override
public void onTaskCompleted(List<PostData> data) {
    PostData[] array = data.toArray(new PostData[data.size()]);
    PostItemAdapter adapter = new PostItemAdapter(getActivity(), R.layout.postitem, array);
    ListView listView = (ListView) getActivity().findViewById(R.id.news_feed_listView);
    listView.setAdapter(adapter);
}

DownloadFile.java

private OnTaskCompleted listener;

public DownloadFile(OnTaskCompleted listener) {
    this.listener = listener;
}

@Override
protected List doInBackground(String... urls) {
    try {
        return loadXmlFromNetwork(urls[0]);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(List result) {
    listener.onTaskCompleted(result);
}


private List loadXmlFromNetwork(String link) throws XmlPullParserException, IOException {
    List<PostData> postData = null;
    InputStream inputStream = null;
    ParseXML parseXML = new ParseXML();
    //String stringHtml = null;

    try {
        inputStream = downloadUrl(link);
        //stringHtml = convertToString(inputStream);              
        postData = parseXML.parse(inputStream);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

    return postData;
}

private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    conn.connect();
    return conn.getInputStream();
}

ParseXML.java

public class ParseXML extends DefaultHandler {

private static final String ns = null;

// Requires InputStream and create a XmlPullParser with a IS input
public List parse(InputStream in) throws XmlPullParserException, IOException {
    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
        return readFeed(parser);
    } finally {
        in.close();
    }
}

private List readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
    List entries = new ArrayList();

    parser.require(XmlPullParser.START_TAG, ns, "channel");
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        if (name.equals("item")) {
            entries.add(readItem(parser));
        }
        else{
            skip(parser);
        }
    }
    return entries;
}

private PostData readItem(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "entry");
    String title = null;
    String description = null;
    String link = null;

    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        if (name.equals("title")) {
            title = readTitle(parser);
        }
        else if (name.equals("link")) {
            link = readLink(parser);
        }
        else if (name.equals("description")) {
            description = readDescription(parser);
        }
    }
    return new PostData(title, link, description);
}

private String readTitle(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "title");
    String title = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "title");
    return title;
}

private String readLink(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "link");
    String link = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "link");
    return link;
}

private String readDescription(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "description");
    String description = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "description");
    return description;
}

private String readText(XmlPullParser parser) throws XmlPullParserException, IOException {
    String result = "";
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.getText();
        parser.nextTag();
    }
    return result;
}

private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
        throw new IllegalStateException();
    }
    int depth = 1;
    while (depth != 0) {
        switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

@Override
protected List doInBackground(String... urls) {
    try {
        return loadXmlFromNetwork(urls[0]);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }

    return null;
}

您将在异常时返回null。请改为Collections.emptyList()

同时将此默认值更改为空列表。

private List loadXmlFromNetwork(String link) throws XmlPullParserException, IOException {
    List<PostData> postData = Collections.<PostData>emptyList();