I'm developing an Xml parsing application. The URL is not trusted when it is opened from the browser. There is no way to correct it from server side. So I used "trsut anybody" code.
But still I'm getting a null pointer exception.
Please help me with this.
Thanx in advance
this is my code.
public class SitesList {
/** Variables */
private ArrayList<String> From_Currency = new ArrayList<String>();
private ArrayList<String> To_Currency = new ArrayList<String>();
private ArrayList<String> exrt_buy = new ArrayList<String>();
private ArrayList<String> exrt_sell = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getFrom_Currency() {
return From_Currency;
}
public void setFrom_Currency(String From_Currency) {
this.From_Currency.add(From_Currency);
}
public ArrayList<String> getTo_Currency() {
return To_Currency;
}
public void setTo_Currency(String To_Currency) {
this.To_Currency.add(To_Currency);
}
public ArrayList<String> getexrt_buy() {
return exrt_buy;
}
public void setexrt_buy(String exrt_buy) {
this.exrt_buy.add(exrt_buy);
}
public ArrayList<String> getexrt_sell() {
return exrt_sell;
}
public void setexrt_sell(String exrt_sell) {
this.exrt_sell.add(exrt_sell);
}
}
MyXMLHandler class
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("DOC"))
{
sitesList = new SitesList();
}
/*} else if (localName.equals("website")) {
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}*/
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("From_Currency"))
sitesList.setFrom_Currency(currentValue);
else if (localName.equalsIgnoreCase("To_Currency"))
sitesList.setTo_Currency(currentValue);
else if (localName.equalsIgnoreCase("exrt_buy"))
sitesList.setexrt_buy(currentValue);
else if (localName.equalsIgnoreCase("exrt_sell"))
sitesList.setexrt_sell(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
XMLParsingExample class
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
URL url;
HttpsURLConnection https;
HttpURLConnection conn = null;
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
url = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
try {
https = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
} else {
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView From_Currency[];
TextView To_Currency[];
TextView exrt_buy[];
TextView exrt_sell[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
From_Currency = new TextView[sitesList.getFrom_Currency().size()];
To_Currency = new TextView[sitesList.getTo_Currency().size()];
exrt_buy = new TextView[sitesList.getexrt_buy().size()];
exrt_sell = new TextView[sitesList.getexrt_sell().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getFrom_Currency().size(); i++) {
From_Currency[i] = new TextView(this);
From_Currency[i].setText("Name = "+sitesList.getFrom_Currency().get(i));
To_Currency[i] = new TextView(this);
To_Currency[i].setText("Website = "+sitesList.getTo_Currency().get(i));
exrt_buy[i] = new TextView(this);
exrt_buy[i].setText("Website Category = "+sitesList.getexrt_buy().get(i));
exrt_sell[i] = new TextView(this);
exrt_sell[i].setText("Website Category = "+sitesList.getexrt_sell().get(i));
layout.addView(From_Currency[i]);
layout.addView(To_Currency[i]);
layout.addView(exrt_buy[i]);
layout.addView(exrt_sell[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
private void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I'm trying to make an api rest call as following:
InputSource is = new InputSource("http://api.eventful.com/rest/events/search?app_key=5mnzXGn4S4WsNxKS&keywords=books&location=paris&date=Future");
is.setEncoding("ISO-8859-1");
ParseurEvent parseur = new ParseurEvent(is);
my event parser:
List<Event> eventList;
InputSource bookXmlFileName;
String tmpValue;
Event eventTmp;
//SimpleDateFormat sdf= new SimpleDateFormat("yy-MM-dd");
//Constructor
public ParseurEvent(InputSource bookXmlFileName) {
this.bookXmlFileName = bookXmlFileName;
eventList = new ArrayList<Event>();
parseDocument();
printDatas();
}
private void parseDocument() {
// parse
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(bookXmlFileName, this);
} catch (ParserConfigurationException e) {
Log.e("myParserConfigurationException", "ParserConfig error");
} catch (SAXException e) {
Log.e("mySAXException", "SAXException : xml not well formed");
} catch (IOException e) {
Log.e("myIOException", e.getMessage());
}
}
public List<Event> printDatas() {
for (Event event : eventList) {
Log.i("Event", event.getTitle());
}
return eventList;
}
#Override
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
if (elementName.equalsIgnoreCase("event")) {
eventTmp = new Event();
eventTmp.setId(attributes.getValue("id"));
}
}
#Override
public void endElement(String s, String s1, String element) throws SAXException {
// if end of book element add to list
if (element.equals("event")) {
eventList.add(eventTmp);
}
if (element.equalsIgnoreCase("title")) {
eventTmp.setTitle(tmpValue);
}
if (element.equalsIgnoreCase("url")) {
eventTmp.setUrl(tmpValue);
}
if (element.equalsIgnoreCase("description")) {
eventTmp.setDescription(tmpValue);
}
if(element.equalsIgnoreCase("start_time")){
eventTmp.setStart_time(tmpValue);
}
}
#Override
public void characters(char[] ac, int i, int j) throws SAXException {
tmpValue = new String(ac, i, j);
}
}
I get this exception:
Couldn't open http://api.eventful.com/rest/events/search?app_key=5mnzXGn4S4WsNxKS&keywords=books&location=paris&date=Future
Any network operation should be done in an AsyncTask. And url.openStream should be helpful in this case.
class ParseTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... n) {
try {
URL url = new URL("http://api.eventful.com/rest/events/search?app_key=5mnzXGn4S4WsNxKS&keywords=books&location=paris&date=Future");
InputStream is = url.openStream();
is.setEncoding("ISO-8859-1");
ParseurEvent parseur = new ParseurEvent(is);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
You can call this task as:
new ParseTask().execute();
Iam getting the data but i want to group some particular data in the form of a group such as in airport list namely
JFK in that all lat,long,name,code of the airport has to make one array similarly the other airports.Please help me the issue.
main java class:
public String getAirportListHTTPURL(String mAirportLocation,Double airportLatitude, Double airportLongitude, String mAirlineCode, boolean mAirport2, String mAddress2, String mCity2, String mState2, String mCountry2) {
String url = CarmelURLConstants.LIVE_URL.toString();
URL u = new URL(url);
URLConnection uc = u.openConnection();
HttpURLConnection http = (HttpURLConnection) uc;
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-type", "text/xml; charset=utf-8");
String xmldata = Here i used the xml format Syntax data
System.out.println(xmldata);
OutputStream out = http.getOutputStream();
Writer wout = new OutputStreamWriter(out);
wout.write(xmldata);
wout.flush();
wout.close();
// Reading Data from the server using getInputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(http.getInputStream()));
System.out.println("code..."+http.getResponseCode());
String result, responsedata = " ";
RequestName = "AirportlistByPickUpAddress Request:-";
ResponseName = "AirportlistByPickupAddress Response:-";
while ((result=rd.readLine()) != null) {
System.out.println(result");
responsedata = result;
// Method to parse in SAX Parser
mParsedValue = ParseAirportLocationResponse(result);
}
// updateTraceFile(xmldata, responsedata,RequestName,ResponseName);
}catch(Exception e){
mParsedValue = e.getMessage();
e.printStackTrace();
}
return mParsedValue;
}
private String ParseAirportLocationResponse(String result) {
try {
// Create a XMLReader from SAXParser
XMLReader mXmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
AirportHandler Airportlist = new AirportHandler();
// Apply Handler to XML Reader
mXmlReader.setContentHandler(Airportlist);
// Start the Process to Parse
InputSource is = new InputSource(new StringReader(result));
mXmlReader.parse(is);
} catch (Exception e) {
System.out.println(e);
}
return result;// Get the Parsed Data
}
In the XMLSETTERS CLASS:
public class XMLGettersSetters {
public static ArrayList<String> airportCode = new ArrayList<String>();
public static ArrayList<String> airportName = new ArrayList<String>();
public static ArrayList<String> latitude = new ArrayList<String>();
public static ArrayList<String> longitude = new ArrayList<String>();
public ArrayList<String> getlongitude() {
return longitude;
}
public void setlongitude(String longitude) {
this.longitude.add(longitude);
Log.i("This is the longitude:", longitude);
}
public ArrayList<String> getairportCode() {
return airportCode;
}
public void setairportCode(String airportCode) {
this.airportCode.add(airportCode);
Log.i("This is the airportCode:", airportCode);
}
public ArrayList<String> getairportName() {
return airportName;
}
public void setairportName(String airportName) {
this.airportName.add(airportName);
Log.i("This is the airportName:", airportName);
}
public ArrayList<String> getlatitude() {
return latitude;
}
public void setlatitude(String latitude) {
this.latitude.add(latitude);
Log.i("This is the latitude:", latitude);
}
}
In the Airport handler class:
public class AirportHandler extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
AirportHandler.data = data;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("getAirportListByPickUpAddressResponse"))
{
data = new XMLGettersSetters();
}
else if (localName.equals("airportList")) {
}
}
/**
* This will be called when the tags of the XML end.
**/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("airportCode"))
data.setairportCode(elementValue);
else if (localName.equalsIgnoreCase("airportName"))
data.setairportName(elementValue);
else if (localName.equalsIgnoreCase("latitude"))
data.setlatitude(elementValue);
else if (localName.equalsIgnoreCase("longitude"))
data.setlongitude(elementValue);
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
After performing XML parsing try like this
ArrayList<String> aList = new ArrayList<String>();
aList.add("your string");
I am making an application for Android and I need to display an XML file of this page:http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009
I tried the solutions given on the page but I find it wrong since it is not displayed when you run the application. I just want to show "tipo= DOLAR SPOT INTERCAMBIO"
This is the XML CODE
and this is my code:
xmlpruebaprueba.jar
XMLdataCollected sitesList= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlpruebaprueba);
//creando un Layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
//creando TextView
TextView Registro[];
TextView Tipo[];
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceURL = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009");
handlingXml HandlingXml = new handlingXml();
xr.setContentHandler(HandlingXml);
xr.parse(new InputSource(sourceURL.openStream()));
}catch (Exception e){
System.out.println("XML Parsing Exception= " + e);
}
sitesList = handlingXml.sitesList;
Registro = new TextView[sitesList.getRegistro().size()];
Tipo = new TextView[sitesList.getTipo().size()];
for (int i = 0; i < sitesList.getRegistro().size(); i++) {
Registro[i] = new TextView(this);
Registro[i].setText("Registro = "+sitesList.getRegistro().get(i));
Tipo[i] = new TextView(this);
Tipo[i].setText("Tipo = "+sitesList.getTipo().get(i));
layout.addView(Registro[i]);
layout.addView(Tipo[i]);
}
}
}
and this is my handler
Boolean currentElement = false;
String currentValue = null;
public static XMLdataCollected sitesList = null;
public static XMLdataCollected getDataCollected (){
return sitesList;
}
public static void setSitesList(XMLdataCollected sitesList){
handlingXml.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
currentElement = true;
if(localName.equals("Root"))
{
sitesList = new XMLdataCollected();
}else if (localName.equals("Registro")){
String attr = attributes.getValue("tipo");
sitesList.setTipo(attr);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
currentElement = false;
if (localName.equalsIgnoreCase("Registro"))
sitesList.setRegistro(currentValue);
else if (localName.equalsIgnoreCase("Root"))
sitesList.setRoot(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
and this is my dataCollected
public class XMLdataCollected {
private ArrayList<String> root = new ArrayList<String>();
private ArrayList<String> registro = new ArrayList<String>();
private ArrayList<String> tipo = new ArrayList<String>();
public ArrayList<String> getRoot (){
return root;
}
public void setRoot(String root){
this.root.add(root);
}
public ArrayList<String> getRegistro (){
return registro;
}
public void setRegistro(String registro){
this.registro.add(registro);
}
public ArrayList<String> getTipo (){
return tipo;
}
public void setTipo(String tipo){
this.tipo.add(tipo);
}
}
You are calling your Web Request on main UI thread.
PLEASE DO NOT DO THIS
use AsyncTask to call web your request.
i parse the xml file and all data will parsed but i dont understand how to set this data in textview ? give me some idea about that
public class GtuItemXMLHandler extends DefaultHandler {
Gtudownload gtudownload;
Questionpaper questionpaper;
// Show me the XML.
private String currentString = "";
private String charactersString = "";
private Branch branch;
private Year year;
private Semester semester;
private int branchCount = 0;
private int yearCount = 0;
private int semesterCount = 0;
// private ArrayList<Gtudownload> itemsList = new ArrayList<Gtudownload>();
//
// public ArrayList<Gtudownload> getItemsList() {
// return itemsList;
// }
public Gtudownload getGtudownload(){
return this.gtudownload;
}
public Questionpaper getQuestionpaper()
{
return this.questionpaper;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i("GTU ", localName);
if (localName.equalsIgnoreCase("Gtudownload")) {
gtudownload = new Gtudownload();
currentString = "Gtudownload";
} else if (localName.equalsIgnoreCase("Questionpaper")) {
gtudownload.setQuestionpaper(new Questionpaper());
gtudownload.getQuestionpaper().setBranchList(new ArrayList<Branch>());
currentString = "Questionpaper";
} else if (localName.equalsIgnoreCase("Branch")) {
branch = new Branch();
gtudownload.getQuestionpaper().getBranchList().add(branch);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).setYearList(new ArrayList<Year>());
currentString = "Branch";
Log.i("Branch", attributes.getValue("value"));
branch.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("Year")) {
year = new Year();
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().add(year);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).setSemesterList(new ArrayList<Semester>());
currentString = "Year";
Log.i("Year ", attributes.getValue("value"));
year.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("semester")) {
semester = new Semester();
currentString = "semester";
Log.i("Semester ", attributes.getValue("value"));
semester.setValue(attributes.getValue("value"));
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().add(semester);
} else if (localName.equalsIgnoreCase("url")){
currentString = "url";
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("Questionpaper")){
branchCount=0;
}else if(localName.equalsIgnoreCase("Branch")){
yearCount = 0;
branchCount++;
}else if(localName.equalsIgnoreCase("Year")){
semesterCount = 0;
yearCount++;
}else if(localName.equalsIgnoreCase("semester")){
semesterCount++;
}else if(localName.equalsIgnoreCase("url")){
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().get(semesterCount).setUrl(charactersString);
Log.i("URL", charactersString);
}
currentString = "";
charactersString= "";
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
charactersString = new String(ch, start, length);
charactersString = charactersString.trim();
}
}
this is my activity and how can i set this parsing data in into textview
public class GtudldActivity extends Activity {
/** Called when the activity is first created. */
private TextView xmlOutput;
TextView example[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
xmlOutput = (TextView) findViewById(R.id.xmlOutput);
Gtudownload gtudownload = parseXML();
}
private Gtudownload parseXML() {
Gtudownload gtudownload = null;
try {
Log.w("AndroidParseXMLActivity", "Start");
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
GtuItemXMLHandler myXMLHandler = new GtuItemXMLHandler();
xr.setContentHandler(myXMLHandler);
InputSource is = new InputSource(getResources().openRawResource(R.raw.mgtu));
gtudownload = myXMLHandler.getGtudownload();
Log.i("Data",gtudownload+"");
xr.parse(is);
} catch (Exception e) {
Log.w("AndroidParseXMLActivity", e);
}
//xmlOutput.setText(gtudownload.toString());
return gtudownload;
}
}
You'll get so many examples for this on google. I am showing you one of the. Just try this
I hope it may help you. If you've any doubt, just post it here
I am trying to use the API for our billing system in an Android Application, but I am having trouble figuring out how to parse the XML that it returns. Here is what my function looks like thus far...
public void ParseData(String xmlData)
{
try
{
// Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
// Input Stream
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlData));
// Parse Document into a NodeList
Document doc = db.parse(inStream);
NodeList nodes = doc.getElementsByTagName("ticket");
// Loop NodeList and Retrieve Element Data
for(int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
if (node instanceof Element)
{
Element child = (Element)node;
String id = child.getAttribute("id");
}
}
}
catch(SAXException e)
{
}
}
and here is what the XML data looks like that is returned. I need to loop through each and pull each element out, but I cant figure out how to do that with the DOM parser.
<whmcsapi>
<action>gettickets</action>
<result>success</result>
<totalresults>1</totalresults>
<startnumber>0</startnumber>
<numreturned>1</numreturned>
<tickets>
<ticket>
<id>1</id>
<tid>557168</tid>
<deptid>1</deptid>
<userid>1</userid>
<name><![CDATA[Array]]></name>
<email></email>
<cc></cc>
<c>TmDEga5v</c>
<date>2009-08-03 23:14:32</date>
<subject><![CDATA[Test Ticket]]></subject>
<message><![CDATA[This is a test ticket>
----------------------------
IP Address: xxx.xxx.xxx.xxx]]></message>
<status>Open</status>
<priority>Medium</priority>
<admin></admin>
<attachment></attachment>
<lastreply>2009-08-04 12:14:18</lastreply>
<flag>0</flag>
<service></service>
</ticket>
</tickets>
</whmcsapi>
Yes SAX parser is the solution and here is the basic code to get you started:
void parseExampleFunction(){
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
File myFile = new File( //the XML file which you need to parse );
myFile.createNewFile();
FileInputStream fOut = new FileInputStream(myFile);
BufferedInputStream bos = new BufferedInputStream( fOut );
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MessagesXMLHandler myXMLHandler = new MessagesXMLHandler(context);
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(bos));
}
// the class where the parsing logic needs to defined.This preferably can be in a different .java file
public class MessagesXMLHandler extends DefaultHandler{
//this function is called automatically when a start tag is encountered
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
//variable localName is the name of the tag
//this function is called autiomatically when an end tag is encountered
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
}
//this function gets called to return the value stored betweeen the closing and opening tags
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
//now variable value has the value stored between the closing and opening tags
String value=new String(ch,start,length);
}
}
for parse xml on android best way is to use SAXParser. i explained it bellow with demo....
first of all create your activity class like as bellw.
public class ActivityForSax extends ListActivity {
private ProgressDialog pDialog;
private ItemXMLHandler myXMLHandler;
private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
private TextView textview;
private ListView mListView;
private ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_dom);
textview = (TextView)findViewById(R.id.textView1);
doParsing();
mListView = getListView();
}
public void doParsing(){
if (isNetworkAvailable()) {
textview.setText("Loading...Please wait...");
new AsyncData().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
class AsyncData extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
menuItems = new ArrayList<HashMap<String, String>>();
pDialog = new ProgressDialog(ActivityForSax.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new ItemXMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
} catch (ParserConfigurationException pce) {
Log.e("SAX XML", "sax parse error", pce);
} catch (SAXException se) {
Log.e("SAX XML", "sax error", se);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
textview.setText("Done!!!");
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
for (int i = 0; i < itemsList.size(); i++) {
Bean objBean = itemsList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("TITLE :: ", objBean.getTitle());
map.put("DESC :: ", objBean.getDesc());
map.put("PUBDATE :: ", objBean.getPubDate());
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(ActivityForSax.this, menuItems,
R.layout.list_item,
new String[] { "TITLE :: ", "DESC :: ", "PUBDATE :: " }, new int[] {
R.id.name, R.id.email, R.id.mobile });
mListView.setAdapter(adapter);
}
}
public void showToast(String msg) {
Toast.makeText(ActivityForSax.this, msg, Toast.LENGTH_LONG).show();
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
now you need to create default handler class for parsing xml data.
public class ItemXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = "";
Bean item = null;
private ArrayList<Bean> itemsList = new ArrayList<Bean>();
public ArrayList<Bean> getItemsList() {
return itemsList;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if (localName.equals("item")) {
item = new Bean();
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equals("id")) {
item.setId(currentValue);
} else if (localName.equals("title")) {
item.setTitle(currentValue);
} else if (localName.equals("desc")) {
item.setDesc(currentValue);
} else if (localName.equals("pubDate")) {
item.setPubDate(currentValue);
} else if (localName.equals("link")) {
item.setLink(currentValue);
} else if (localName.equals("item")) {
itemsList.add(item);
}
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}
and finally your Bean class like as...
public class Bean {
private String id;
private String title;
private String desc;
private String pubDate;
private String link;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
Add java-json.jar in library folder
Compile files ('libs/java-json.jar') //add this line into your build
Here is the code to convert xml response to json response:
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}