2

您好,感谢您的帮助。

我正在解析从 URL 检索的 XML。

但是当我在几秒钟后调用解析器时,我崩溃并得到一个 java.lang.NullPointerException

特别是,这是代码:

public class AndroidXMLParsingActivity extends Activity {

// All static variables
static final String URL = "http://www.nation.co.ke/news.xml";
public ArrayList<Article> articoli;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView lv = (ListView) findViewById(R.id.list);
    String xml = getXmlFromUrl(URL);
    InputSource source = new InputSource(new StringReader(xml));

    try {
        articoli = ReadXMLFileUsingSaxparser.parsa(source);
    } catch (Exception e) {
        Log.e("ERRROR", e.toString());
    }
    ListAdapter adapter = new NewsAdapter(this, articoli);
    lv.setAdapter(adapter);
}

public static String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

}

那么articoli 从对 ReadXMLFileUsingSaxparser.parsa(source) 的调用返回 null

这是解析器的代码。

public class ReadXMLFileUsingSaxparser extends DefaultHandler {
private Article acct;
private String temp;
private static ArrayList<Article> accList = new ArrayList<Article>();
/** The main method sets things up for parsing */
public static ArrayList<Article> parsa(InputSource xml) throws IOException, SAXException,
              ParserConfigurationException {

       //Create a "parser factory" for creating SAX parsers
       SAXParserFactory spfac = SAXParserFactory.newInstance();

       //Now use the parser factory to create a SAXParser object
       SAXParser sp = spfac.newSAXParser();

       //Create an instance of this class; it defines all the handler methods
       ReadXMLFileUsingSaxparser handler = new ReadXMLFileUsingSaxparser();

       //Finally, tell the parser to parse the input and notify the handler
       sp.parse(xml, handler);

       handler.readList();
    return accList;

}
/*
 * When the parser encounters plain text (not XML elements),
 * it calls(this method, which accumulates them in a string buffer
 */
public void characters(char[] buffer, int start, int length) {
       temp = new String(buffer, start, length);
}
/*
 * Every time the parser encounters the beginning of a new element,
 * it calls this method, which resets the string buffer
 */ 
public void startElement(String uri, String localName,
              String qName, Attributes attributes) throws SAXException {
       temp = "";
       if (qName.equalsIgnoreCase("item")) {
              acct = new Article();
       }
}
/*
 * When the parser encounters the end of an element, it calls this method
 */
public void endElement(String uri, String localName, String qName)
              throws SAXException {
       if (qName.equalsIgnoreCase("item")) {
              // add it to the list
              accList.add(acct);
       } else if (qName.equalsIgnoreCase("title")) {
              acct.title=temp;
       } else if (qName.equalsIgnoreCase("description")) {
              acct.description=temp;
       } else if (qName.equalsIgnoreCase("articleDate")) {
           acct.articleDate=temp;          
       } else if (qName.equalsIgnoreCase("story")) {
           acct.story=temp;            
       } else if (qName.equalsIgnoreCase("author")) {
           acct.author=temp;           
       } else if (qName.equalsIgnoreCase("photo")) {
           acct.photo=temp;            
       } else if (qName.equalsIgnoreCase("caption")) {
           acct.caption=temp;          
       } else if (qName.equalsIgnoreCase("link")) {
           acct.link=temp;             
       } else if (qName.equalsIgnoreCase("video")) {
           acct.video=temp;            
       }
}

private void readList() {
       Log.e("","No of  the accounts in bank '" + accList.size()  + "'.");
       Iterator<Article> it = accList.iterator();
       int i=0;
       while (it.hasNext()) {
           Log.e("STORY " + Integer.toString(i),it.next().story);
           i++;
       }
} 
}
4

3 回答 3

1

我的猜测是当你遇到 NullPointer

try {
    articoli = ReadXMLFileUsingSaxparser.parsa(source);
} catch (Exception e) {
    Log.e("ERRROR", e.toString());
}

ListAdapter adapter = new NewsAdapter(this, articoli);
lv.setAdapter(adapter);

失败,因此您使用为空的适配器初始化 ListView。只需在 catch 块中初始化 articoli ArrayList,避免 Parser 内部崩溃或进行 != null 检查。

于 2013-08-15T19:26:13.863 回答
1

这里有例子。http://androidcodesnips.blogspot.com/2011/04/sax-parsing.html

这将帮助您为 xml 设置一个 sax 解析器

于 2013-08-15T19:20:51.357 回答
1
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView lv = (ListView) findViewById(R.id.list);
    String xml = getXmlFromUrl(URL);
    InputSource source = new InputSource(new StringReader(xml));

    try {
        articoli = ReadXMLFileUsingSaxparser.parsa(source);
    } catch (Exception e) {
        Log.e("ERRROR", e.toString());
    }
    if(articoli != null){
        ListAdapter adapter = new NewsAdapter(this, articoli);
        lv.setAdapter(adapter);
    }
    else{
       // TODO: show message to the user about xml data is invalid or you have network connection error or so on

       finish(); // return to the previous Activity.
    }
}
于 2013-08-15T19:25:35.480 回答