我有爲Android 2.2編寫的代碼,應該將xml從網頁解析爲字符串。它在Android 2.2模擬器上工作正常,但它在我的Android 3.1平板電腦上給了我一個NullPointerException。下面是代碼:Android 3.1 Xml解析NullPointerException
Log.d("refreshMeta", "refreshing meta.");
url = new URL("http://www.chineseoutreach.ca/media/Cstreaming.xml");
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
Log.d("Connection","connected");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("nowplaying");
Element entry = (Element)nl.item(0);
try {
Element eartist = (Element)entry.getElementsByTagName("artist").item(0);
sartist = eartist.getFirstChild().getNodeValue();
Log.d("Artist",sartist);
}
catch(NullPointerException e) {
sartist = "";
Log.d("Connection",e.toString());
}
登錄Android上3:
refreshmeta:清爽元。
連接:連接
連接:顯示java.lang.NullPointerException
EDIT 這是引起它的行。元素eartist =(Element)entry.getElementsByTagName(「artist」)。item(0);
編輯2
07-28 13:10:01.483:ERROR /空(6189):我的消息
07-28 13:10:01.483:ERROR /空(6189):JAVA。 lang.NullPointerException
07-28 13:10:01.483:ERROR /空(6189):在com.ciam.app.CiamInfoActivity.refreshMeta(CiamInfoActivity.java:280)
07-28 13:10 :01.483:錯誤/空(6189):at com.ciam.app.CiamInfoActivity.access $ 0(CiamInfoActivity.java:257)
07:28:13:10:01.483:ERROR/Null(6189):at com.ciam.app.CiamInfoActivity $ 2.run(CiamInfoActivity.java:123) 07-28 13:10:01.483:ERROR/Null (6189):在java.lang.Thread.run(Thread.java:1020)
我懷疑在android 2和android 3上解析xml的方式有一些區別。任何想法?提前致謝。
不要使用'Log.d()'登錄catch塊。使用Log.e(LOG_TAG,「我的消息」,e)'。比你會看到一個堆棧跟蹤,它顯示你哪一行... – WarrenFaith
謝謝。實施它。 – gammaraptor