I have code written for Android 2.2 that is supposed to parse xml from a webpage to a String. It works fine on an Android 2.2 emulator, but it gives me a NullPointerException on my Android 3.1 tablet. Here is the code:
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());
}
Log on Android 3:
refreshmeta: refreshing meta.
Connection: Connected
Connection: java.lang.NullPointerException
EDIT
This is the line that causes it.
Element eartist = (Element)entry.getElementsByTagName(“artist”).item(0);
Edit 2
07-28 13:10:01.483: ERROR/Null(6189): my message
07-28 13:10:01.483: ERROR/Null(6189): java.lang.NullPointerException
07-28 13:10:01.483: ERROR/Null(6189): at com.ciam.app.CiamInfoActivity.refreshMeta(CiamInfoActivity.java:280)
07-28 13:10:01.483: ERROR/Null(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): at java.lang.Thread.run(Thread.java:1020)
I suspect that there are some differences between the way xml is parsed on android 2 and android 3. Any ideas? Thanks in advance.
There is a small mistake in your code. I don’t really understand why it was working with android 2.1 emu, but it shouldn’t have. Your problem was that you were doing a dom.getDocumentElement(). That function will return the base tag of your xml file which is in this case “nowplaying”. And then you are doing a “docEle.getElementsByTagName(“nowplaying”);” over that.
If you want to be sure to get “nowplaying”, you have to do a “dom.getElementsByTagName(“nowplaying”)”.
Corrected version: