Parse XML on Android - android

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();
}

Related

Api rest call in android doesn't work

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();

Getting xml data and to store in the form of array list

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");

parsing XML online file Android

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.

how to do nested parsing using SAX Parser in android

I have a xml like this :
<channel>
<item>
<link>http://uopnews.unipune.ac.in/Lists/Calendar/DispForm.aspx?ID=14</link>
<description><![CDATA[<div><b>Location:</b> PUMBA Auditorium - University of Pune</div> <div><b>Start Time:</b> 5/15/2012 11:00 AM</div>
<div><b>End Time:</b> 5/15/2012 2:00 PM</div>
<div><b>Description:</b> <div>General B. C. Joshi Memorial Lecture 2012- Perspective on War in the 21st Century - By Lt. Gen. A. K. Singh</div></div>
<div><b>Attachments:</b> http://uopnews.unipune.ac.in/Lists/Calendar/Attachments/14/bcjoshi2012[1].pdf<br></div>
]]></description>
</item>
</channel>
I can parse upto description tag using SAX Parser here is my SAXhandler class.
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.R.string;
import android.util.Log;
public class XMLParsingHandler extends DefaultHandler {
private static final String NEW_DATA_SET = "image";
private String currentValue = "";
private String currentTag = "";
private HashMap<String, Object> root;
private HashMap<String, String> child;
private String[] tagArray = null;
private ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
private String describe;
public XMLParsingHandler(String[] tagArray) {
this.tagArray = tagArray;
}
public void parseContent(String urlStr) {
try {
URL url = new URL(urlStr);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
xmlReader.parse(new InputSource(url.openStream()));
Log.d("PRASER", "Afer parsering done" + arraylist);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
root = new HashMap<String, Object>();
System.out.println("root=" + root);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
Log.d("tag", "StartElement started here");
currentTag = localName;
Log.d("start", "in start doc current atg---------: " + currentTag);
if (localName.equals(NEW_DATA_SET)) {
child = new HashMap<String, String>();
currentValue = new String();
}
describe=new String();
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
currentValue = new String(ch, start, length);
Log.d("other", "in CHARACTER : CurrentValue=---------" + currentValue
+ " currentTag-------" + currentTag);
if(currentTag.equals("description") ) {
String str= new String(ch, start, length);
//describe=new String();
describe=describe+""+currentValue;
Log.d("describe", "in CHARACTER : describe=---------" + describe);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
Log.d("end", "currentTag:"+currentTag+"------currentValue"+currentValue);
if(child!=null)
{
for (int i = 0; i < tagArray.length; i++) {
if (currentTag.equals("description")){
child.put(currentTag, currentValue);
}
if (currentTag.equals(tagArray[i]))
{
child.put(currentTag, currentValue);
Log.d("tagarray","currentTag="+ currentTag+"currentValue:"+currentValue);
currentValue=null;
currentValue=new String();
currentTag=null;
currentTag=new String();
}
}
if (localName.equals(tagArray[tagArray.length - 1])) {
arraylist.add(child);
child=null;
child=new HashMap<String, String>();
}
}
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
Log.d("tag", "in end doc");
}
public ArrayList<HashMap<String, String>> getArraylist() {
return arraylist;
}
public void setArraylist(ArrayList<HashMap<String, String>> arraylist) {
this.arraylist = arraylist;
}
#Override
public String toString() {
return arraylist.toString();
}
}
and I am Calling it like this :
userMap = new HashMap<String, String>();
XMLParsingHandler x = new XMLParsingHandler(tagArray);
x.parseContent(url);
System.out.println("Element FOund");
userMap = x.getArraylist().get(0);
System.out.println("Map " + userMap);
here my userMap only print valu upto description tag after it only shows null value. i need all data from description. Is there any way?
Find the below sax parser code
public class IndianNewsHandler implements ContentHandler {
private String value = "";
private Item item = null;
private TextView tvRef = null;
private Activity myActivity = null;
private static IndianNewsHandler mIndianNewsHandler;
public static IndianNewsHandler getInstance() {
if (mIndianNewsHandler == null) {
mIndianNewsHandler = new IndianNewsHandler();
}
return mIndianNewsHandler;
}
private IndianNewsHandler() {
}
private ArrayList<Item> content = new ArrayList<Item>();
// private ArrayList<String> myList = new ArrayList<String>();
private boolean STATUS_PARSE = true;
private boolean ITEM_STATUS = false;
public ArrayList<Item> getData() {
return content;
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (STATUS_PARSE) {
this.value = localName;
if (localName.equals("item")) {
item = new Item();
ITEM_STATUS = true;
}
}
}
public void characters(char[] text, int start, int length)
throws SAXException {
if (STATUS_PARSE && ITEM_STATUS) {
StringBuffer buffer = new StringBuffer();
buffer.append(text, 0, length);
if (buffer != null) {
if (this.value.equals("title")) {
System.out.println("I am in title"
+ buffer.toString().trim());
if (buffer.toString().trim().length() > 1)
item.setTitle(buffer.toString().trim());
} else if (value.equals("description"))
{
String url = buffer.toString().trim();
try {
if (url.contains("img src=")) {
final String url_string = url.split("img src=")[1]
.split(">")[0].replace("'", "");
System.out.println("FInal URL :" + url_string);
if (url_string != null) {
//here i am creating async task for convert image
new CovertingImageToByte(url_string).execute();
if (buffer.toString().trim().length() > 1) {
String des = buffer.toString().split(">")[1];
item.setDes(des);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class CovertingImageToByte extends AsyncTask<String,Integer, String>{
String imageUrl;
public CovertingImageToByte(String urlString) {
this.imageUrl=urlString;
}
#Override
protected String doInBackground(String... params) {
try {
InputStream is = new URL(imageUrl)
.openStream();
Bitmap bitmap = BitmapFactory
.decodeStream(is);
byte[] mybyt = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG,
0, stream);
mybyt = stream.toByteArray();
System.out.println("test"
+ mybyt.length);
item.setImg(mybyt);
// System.out.println("Finallly List123 size ::::::::::"+content.get(0).getImg().length);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (STATUS_PARSE) {
if (localName.equals("item")) {
content.add(item);
}
if (content.size() >= 15) {
STATUS_PARSE = false;
}
}
}
#Override
// do nothing methods
public void setDocumentLocator(Locator locator) {
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
System.out.println("Finallly List size ::::::::::" + content.get(1));
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {
}
public void skippedEntity(String name) throws SAXException {
}
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException {
}
public void processingInstruction(String target, String data)
throws SAXException {
}
}

how to set data in textbox after sax parsing

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

Categories

Resources