I am just starting out in android app development although I do have some knowledge of java.
So my app needs both local & internet based xml files
to be parsed. I did manage to parse them locally but I have been trying for quite some time to parse the xml files on internet but no success.
I have used both XML Pull Parser & SAX Parser
. Moreover, I have also tried multiple XML files but no progress. I am posting a sample code of SAX Parser
consisting of one of the sample XML files on a url.
In the program, all I am trying to do is to just read a simple attribute from an element but the file can not be read.
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class WeatherXMLParsing extends Activity
{
TextView tv;
static final String baseUrl="http://gunsnroses23.zxq.net/ak/catalog.xml";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
tv = (TextView) findViewById(R.id.tv1);
try
{
URL website= new URL(baseUrl);
//setting up XMLReader & SAXParser to parse data
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
XMLReader xr=sp.getXMLReader();
HandlingXMLStuff doingWork= new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String information=doingWork.getinformation();
tv.setText(information);
}
catch (Exception e)
{
tv.setText("Error");
}
}
}
public class XMLDataCollected {
String catalog=null;
public void setCatalog(String c){
catalog=c;
}
public String datatoString(){
return "The attribute of catalog is " +catalog;
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HandlingXMLStuff extends DefaultHandler
{
private XMLDataCollected info=new XMLDataCollected();
public String getinformation(){
return info.datatoString();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
// TODO Auto-generated method stub
if (localName.equals("catalog")){
String catalog=attributes.getValue("journal");
info.setCatalog(catalog);
}
}
}
Any help would be greatly appreciated. Thank you.
Update:
I want to thank you to all those who replied to my query. Thank you so much but the problem has been resolved. There was no problem with the code. The only simple problem was the "internet" permission was not defined in AndroidManifest.xml. That is what I have been thinking after going through the code again & again. I could not find any issue since it is such a simple code but thank you, everyone.