@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.
}
}
Why do I get java.lang.NullPointerException parsing XML from an URL? (and how to fix it?)
-
24-06-2022 - |
Domanda
Hi and thanks for your help.
I am parsing an XML that I retrieve from an URL.
But when I call the parser after some seconds I crash and get an java.lang.NullPointerException
In particular, this is the code:
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;
}
}
Well articoli returns null form the call to ReadXMLFileUsingSaxparser.parsa(source)
This is the code of the parser.
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++;
}
}
}
Soluzione
Altri suggerimenti
Here example is there. http://androidcodesnips.blogspot.com/2011/04/sax-parsing.html
which will help you setup a sax parser for xml
My guess is that you are running into the NullPointer when
try {
articoli = ReadXMLFileUsingSaxparser.parsa(source);
} catch (Exception e) {
Log.e("ERRROR", e.toString());
}
ListAdapter adapter = new NewsAdapter(this, articoli);
lv.setAdapter(adapter);
fails so that you initialize your ListView with an adapter that is null. Simply initialize the articoli ArrayList inside the catch block, avoid crashes inside the Parser or make an != null check.