I want to read an .xml file from a web radio for my app.
I’ve used this tutorial: http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
This is the function:
public String leggi_palinsesto(){
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < 1; i++) {
Element e = null;
String titolo = parser.getValue(e, KEY_TITOLO); // name child value
String artista = parser.getValue(e, KEY_ARTISTA); // cost child value
System.out.println(artista+" - "+titolo);
}
return titolo+" "+artista;
}
But when arrive to NodeList nl = doc.getElementsByTagName(KEY_ITEM); the app crashes.
This is the logcat:
06-28 18:27:58.089: E/AndroidRuntime(1050): FATAL EXCEPTION: main
06-28 18:27:58.089: E/AndroidRuntime(1050): java.lang.NullPointerException
06-28 18:27:58.089: E/AndroidRuntime(1050): at it.axiomatic.radioamicizia.RadioAmiciziaActivity.leggi_palinsesto(RadioAmiciziaActivity.java:315)
06-28 18:27:58.089: E/AndroidRuntime(1050): at it.axiomatic.radioamicizia.RadioAmiciziaActivity$1$1.run(RadioAmiciziaActivity.java:122)
06-28 18:27:58.089: E/AndroidRuntime(1050): at android.os.Handler.handleCallback(Handler.java:587)
06-28 18:27:58.089: E/AndroidRuntime(1050): at android.os.Handler.dispatchMessage(Handler.java:92)
06-28 18:27:58.089: E/AndroidRuntime(1050): at android.os.Looper.loop(Looper.java:123)
06-28 18:27:58.089: E/AndroidRuntime(1050): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-28 18:27:58.089: E/AndroidRuntime(1050): at java.lang.reflect.Method.invokeNative(Native Method)
06-28 18:27:58.089: E/AndroidRuntime(1050): at java.lang.reflect.Method.invoke(Method.java:521)
06-28 18:27:58.089: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-28 18:27:58.089: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-28 18:27:58.089: E/AndroidRuntime(1050): at dalvik.system.NativeStart.main(Native Method)
This is the constant:
static final String URL = "http://www.radioamicizia.com/demo.xml";
// XML node keys
static final String KEY_ITEM = "song"; // parent node
static final String KEY_TITOLO = "Title";
static final String KEY_ARTISTA = "Artist";
Could someone please help me with this problem.
The doc variable is null, and so attempting to call getElementByTagName on it throws the NPE.
It comes from the parser.getDomElement(xml) or before it.
In short, make sure you followed the tutorial in full and your XmlParser class is exactly as in the tutorial and the methods dont return null.
Also, learn to attach a debugger to your process, set a breakpoint, and inspect your code that way, I suggest you use Intellij community edition,i ts quite easy. 🙂