2

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++;
       }
} 
}
6
  • pls mark the row with nullpointer exception ( look at stack trace) and fix it by checking that wariable if is null Commented Aug 15, 2013 at 19:18
  • If you look at your logcat, the NullPointerException should be coming from a specific line in the ReadXMLFileUsingSaxparser. Please tell us what line that is Commented Aug 15, 2013 at 19:22
  • @matheszabi thanks, this would help avoiding crash, but it will not solve the problem, because, naturally, I need the ArrayList "articoli" not to be null Commented Aug 15, 2013 at 19:22
  • @VishwaPatel "articoli" returns null form the call of the method "ReadXMLFileUsingSaxparser.parsa(source)" not form inside the class "ReadXMLFileUsingSaxparser". So everything works fine but when I try to use "articoli" for a ListView there I get the NullPointerException Commented Aug 15, 2013 at 19:25
  • articoli = ReadXMLFileUsingSaxparser.parsa(source); should newer return null, because of private static ArrayList<Article> accList = new ArrayList<Article>(); return accList; Commented Aug 15, 2013 at 19:36

3 Answers 3

1
@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.
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! But again it does not solve the issue, becuase I need "articoli" to be returned not null :-)
@LisaAnne try to parse the xml from www.matheszabi.com/inexistent.xml what will return is a null or not? where you check the xml is an expected format or not?
it gives Nullpointer but at String xml=getXmlFromUrl(URL) indeed www.matheszabi.com/inexistent.xml is non existent
1

Here example is there. http://androidcodesnips.blogspot.com/2011/04/sax-parsing.html

which will help you setup a sax parser for xml

Comments

1

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.

2 Comments

thanks! But again it does not solve the issue, because I need "articoli" to be returned not null :-)
Well then you need to fix the .parsa() method so that it doesnt return null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.