【问题标题】:Why do I get java.lang.NullPointerException parsing XML from an URL? (and how to fix it?)为什么我从 URL 解析 XML 时得到 java.lang.NullPointerException? (以及如何解决它?)
【发布时间】:2013-08-18 01:47:49
【问题描述】:

您好,感谢您的帮助。

我正在解析从 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++;
       }
} 
}

【问题讨论】:

  • 请用 nullpointer 异常标记该行(查看堆栈跟踪)并通过检查 wariable if 是否为 null 来修复它
  • 如果您查看 logcat,NullPointerException 应该来自 ReadXMLFileUsingSaxparser 中的特定行。请告诉我们这是哪一行
  • @matheszabi 谢谢,这将有助于避免崩溃,但它不会解决问题,因为,自然地,我需要 ArrayList "articoli" 不为空
  • @VishwaPatel "articoli" 从方法 "ReadXMLFileUsingSaxparser.parsa(source)" 的调用返回空值,而不是在类 "ReadXMLFileUsingSaxparser" 中的形式。所以一切正常,但是当我尝试将“articoli”用于 ListView 时,我得到 NullPointerException
  • articoli = ReadXMLFileUsingSaxparser.parsa(source); 应该更新返回 null,因为 private static ArrayList&lt;Article&gt; accList = new ArrayList&lt;Article&gt;(); return accList;

标签: android url nullpointerexception saxparser


【解决方案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 检查。

【讨论】:

  • 谢谢!但同样它并没有解决问题,因为我需要返回“articoli”而不是 null :-)
  • 那么您需要修复 .parsa() 方法,使其不返回 null。
【解决方案2】:
@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.
    }
}

【讨论】:

  • 谢谢!但同样它不能解决问题,因为我需要返回“articoli”而不是 null :-)
  • @LisaAnne 尝试解析来自 www.matheszabi.com/inexistent.xml 的 xml 什么会返回 null 与否?你在哪里检查 xml 是否是预期的格式?
  • 它给出了 Nullpointer 但在 String xml=getXmlFromUrl(URL) 确实 www.matheszabi.com/inexistent.xml 不存在
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多