I am creating the recovery of text using XML from a URL. I get the text. But I have a problem.
When the text of an item of the XML is large, in the TextView not shows all text of the XML.
What can be the error?
ACTIVITY
class tareaAsyncHorariosTarifas extends AsyncTask<Void, Void, Void> {
XmlReader helper;
#Override
protected Void doInBackground(Void... params) {
helper = new XmlReader(color);
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getHorarios());
}
if(builder.toString().equals("")) {
horario2.setText("-");
} else {
horario2.setText(Html.fromHtml(builder.toString()));
}
builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getTarifas());
}
if(builder.toString().equals("")) {
tarifa2.setText("-");
} else {
tarifa2.setText(Html.fromHtml(builder.toString()));
}
}
}
XML READER
public XmlReader(String color) {
this.color = color;
}
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(URL + color + ".xml").openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) {
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currTag = true;
currTagVal = "";
if (localName.equals("color")) {
post = new HorariosTarifasObj();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("horarios")) {
post.setHorarios(currTagVal);
} else if(localName.equalsIgnoreCase("tarifas")) {
post.setTarifas(currTagVal);
} else if (localName.equalsIgnoreCase("color")) {
posts.add(post);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
Related
In internet I got a code to download the text of an XML from a URL. The works ok. My problem is that I have to download many XML simultaneously.
I can to improve my code to make downloading faster? thanks
XMLParser
public XmlReader(String monumento) {
this.monumento = monumento;
}
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(URL + monumento + ".xml").openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) {
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currTag = true;
currTagVal = "";
if (localName.equals("monumento")) {
post = new HorariosTarifasObj();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("horarios")) {
post.setHorarios(currTagVal);
} else if(localName.equalsIgnoreCase("tarifas")) {
post.setTarifas(currTagVal);
} else if (localName.equalsIgnoreCase("monumento")) {
posts.add(post);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
ACTIVITY.java
class tareaAsyncHorariosTarifas extends AsyncTask<Void, Void, Void> {
XmlReader helper;
#Override
protected Void doInBackground(Void... params) {
helper = new XmlReader(monumento);
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getHorarios());
}
if(builder.toString().equals("")) {
horario2.setText("-");
} else {
horario2.setText(Html.fromHtml(builder.toString()));
}
builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getTarifas());
}
if(builder.toString().equals("")) {
tarifa2.setText("-");
} else {
tarifa2.setText(Html.fromHtml(builder.toString()));
}
}
}
my XML Content: (FileName: sku.xml)
<skus>
<id>p1</id>
<id>test</id>
<id>aa</id>
<id>bb</id>
<id>cc</id>
<id>dd</id>
<id>ee</id>
<id>ff</id>
<id>gg</id>
<id>hh</id>
<id>ii</id>
<id>jj</id>
<id>kk</id>
<id>ll</id>
</skus>
my SAX XML PARSER Class:
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
List<XMLSetAdd> setAdds = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// get the News list`
setAdds = saxHandler.getIds();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return News list
return setAdds;
}
}
My SAX XML HANDLER:
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equals("skus")) {
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("skus")) {
setAdds.add(setAdd);
} else if (qName.equals("id")) {
setAdd.setId(tempVal);
}
}
}
my XML SetAdd:
public class XMLSetAdd {
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
private String Id;
}
My Async Class:
private class GetXMLTask extends AsyncTask<String, Void, List<XMLSetAdd>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(List<XMLSetAdd> news) {
try
{
for (int i = 0; i < IdsL.size(); i++)
{
skusList.add(IdsL.get(i).getId());
Log.d("XML content",IdsL.get(i).getId());
}
skusQuery = new Bundle();
skusQuery.putStringArrayList("ITEM_ID_LIST", skusList);
GetAllSkusAsync runner = new GetAllSkusAsync();//Some Async to run after
runner.execute();
}
catch (Exception ex)
{
Log.d("Error Reading XML: ", ex.toString());
Toast.makeText(
getApplicationContext(),"Connection Error!"
Toast.LENGTH_SHORT).show();
}
}
/*
* uses HttpURLConnection to make Http request from Android to download
* the XML file
*/
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
Log.d("Error in asyncTask XML: ", ex.toString());
ex.printStackTrace();
}
return output.toString();
}
private List<XMLSetAdd> IdsL;
#Override
protected List<XMLSetAdd> doInBackground(String... urls) {
IdsL = null;
List<XMLSetAdd> myList = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
IdsL = SAXXMLParser.parse(stream);
myList = SAXXMLParser.parse(stream);
}
// stream.close();
return IdsL;
}
}
The code which I use to call Async Class:
String URL = "http://someaddress/php/sku.xml";
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
Now When I run this code and Log the result ,my list returns the last xml child which based on my xml file is "ll" and the rest of xml is not added to the file.
The list should return all of the ids but returns the last one.
Check following code. Edited SAX XML HANDLER.
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equals("skus")) {
setAdds = new List<XMLSetAdd>();
}else if(qName.equals("id")){
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("skus")) {
} else if (qName.equals("id")) {
setAdd.setId(tempVal);
setAdds.add(setAdd);
}
}
}
The reason is because you are only adding items to the list when endElement is skus. You should be adding one element for each id as follows:
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("skus")) {
// setAdds.add(setAdd); // dont add here..
} else if (qName.equals("id")) {
setAdd.setId(tempVal); // if ending with id
setAdds.add(setAdd); // then add id to the list
}
}
Update
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equals("id")) {
setAdd = new XMLSetAdd(); // new item for each id
}
}
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
curentElement=localName;
if(qName.equals("skus")){
setAdd = new XMLSetAdd();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
String value = new String(ch, start, length);
if(curentElement.equals("id")){
tempVal=value;
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
curentElement = "";
if (localName.equals("id")) {
setAdd.setId(tempVal);
}else if(localName="skus"){
setAdds.add(setAdd);
}
Try this way
Update your parse
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
// Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// reset
if (qName.equals("id")) {
tempVal = "";
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("id")) {
setAdd.setId(tempVal);
setAdds.add(setAdd);
}
}
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'm a noob to android and I'm trying to learn how to parse xml with the SAX parser. I've written a test application to try to implement it, but i can't seem to make it work. I want my textview to display corresponding values from an xml but it's not working. Can anyone help?
Parser
public class ParseTestActivity extends Activity implements View.OnClickListener {
/** Called when the activity is first created. */
final static String TAG = "spotxml";
TextView tv;
WebView xml;
Button help, help2;
int livespot = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1parsed);
help = (Button) findViewById(R.id.button1);
help2 = (Button) findViewById(R.id.button2);
help.setOnClickListener(this);
help2.setOnClickListener(this);
xml = (WebView) findViewById(R.id.webView1);
try{
xml.loadUrl("http://www.xmlcharts.com/cache/precious-metals.xml");
}catch (Exception e){
e.printStackTrace();
}
try{
URL xmlcharts = new URL("http://www.xmlcharts.com/cache/precious-metals.xml");
//InputSource local = new InputSource(getResources().openRawResource(R.raw.preciousmetals));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(xmlcharts.openStream()));
//xr.parse(local);
XMLDataCollected information = doingWork.getInformation();
//String information = doingWork.getInformation();
tv.setText(information.toString());
livespot = Integer.parseInt(information.toString());
}catch(Exception e){
Toast.makeText(ParseTestActivity.this, "Error", Toast.LENGTH_LONG).show();
Log.e(TAG, "WeatherQueryError", e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
try{
URL xmlcharts = new URL("http://www.xmlcharts.com/cache/precious-metals.xml");
//InputSource local = new InputSource(getResources().openRawResource(R.raw.preciousmetals));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(xmlcharts.openStream()));
//xr.parse(local);
XMLDataCollected information = doingWork.getInformation();
//String information = doingWork.getInformation();
tv.setText(information.toString());
livespot = Integer.parseInt(information.toString());
}catch(Exception e){
Toast.makeText(ParseTestActivity.this, "Error", Toast.LENGTH_LONG).show();
Log.e(TAG, "WeatherQueryError", e);
}
break;
case R.id.button2:
try{
//URL xmlcharts = new URL("http://www.xmlcharts.com/cache/precious-metals.xml");
InputSource local = new InputSource(getResources().openRawResource(R.raw.preciousmetals));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
//xr.parse(new InputSource(xmlcharts.openStream()));
xr.parse(local);
XMLDataCollected information = doingWork.getInformation();
//String information = doingWork.getInformation();
tv.setText(information.toString());
livespot = Integer.parseInt(information.toString());
}catch(Exception e){
Toast.makeText(ParseTestActivity.this, "Error", Toast.LENGTH_LONG).show();
Log.e(TAG, "WeatherQueryError", e);
}
break;
}
}}
Content Handler
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HandlingXMLStuff extends DefaultHandler {
private boolean in_prices = false;
private boolean in_pricelist = false;
private boolean in_uspricegold = false;
private boolean in_uspricesilver = false;
String gs = null;
String ss = null;
private XMLDataCollected info = new XMLDataCollected();
//public String getInformation(){
// return info.datatoString();
//}
public XMLDataCollected getInformation(){
return this.info;
}
#Override
public void startDocument() throws SAXException {
this.info = new XMLDataCollected();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("prices")) {
this.in_prices = true ;
}else if (localName.equalsIgnoreCase("pricelist")) {
String attrValue = attributes.getValue("currency");
if (attrValue.equalsIgnoreCase("usd")){
this.in_pricelist = true;
}else if (localName.equalsIgnoreCase("price")){
String attrValue2 = attributes.getValue("commodity");
if (attrValue2.equalsIgnoreCase("gold")){
this.in_uspricegold = true;
}else if (localName.equalsIgnoreCase("price")){
String attrValue3 = attributes.getValue("commodity");
if (attrValue3.equalsIgnoreCase("silver")){
this.in_uspricesilver = true;
}
}}}
}
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("prices")) {
this.in_prices = false;
}else if (localName.equalsIgnoreCase("pricelist")) {
this.in_pricelist = false;
}else if (localName.equalsIgnoreCase("price")) {
this.in_uspricegold = false;
}else if (localName.equalsIgnoreCase("price")) {
this.in_uspricesilver = false;
}
}
#Override
public void characters(char[] ch, int start, int length)throws SAXException {
if(this.in_uspricegold) {
//info.setSpotGold(new String (ch, start, length));
//}
int spotgold = Integer.parseInt(new String (ch, start, length));
info.setSpotGold(spotgold);
this.in_uspricegold = false;
}else{}
if(this.in_uspricesilver){
//info.setSpotSilver(new String(ch, start, length));
// }
int spotsilver = Integer.parseInt(new String(ch, start, length));
info.setSpotSilver(spotsilver);
this.in_uspricesilver = false;
}else{}
}
}
Collected Data Set
public class XMLDataCollected{
private int spotsilver = 0;
private int spotgold = 0;
public int getSpotGold() {
return spotgold;
}
public void setSpotGold(int spotgold){
this.spotgold = spotgold;
}
public int getSpotSilver() {
return spotsilver;
}
public void setSpotSilver(int spotsilver){
this.spotsilver = spotsilver;
}
public String toString(){
return "gold " + spotgold + " silver "+ spotsilver;
}
}
First of all your method characters has to be much simpler. The only thing that it does is to read the characters between the tags. It will be like this:
public void characters(char[] ch, int start, int end) {
buffer.append(new String(ch, start, end));
}
As you can see I'm using a StringBuffer as a private field. It's instantiate at the beginning of the startElement method and "resetted" at the beginning of the endElement.
value = buffer.toString();
buffer.setLength(0);
The field value will actually keep the real value of the field.
All my class for reference:
private String value;
private StringBuffer buffer;
#Override
public void startElement(
String nameSpaceURI,
String localName,
String qName,
Attributes atts
) {
buffer = new StringBuffer();
if(localName.equals("myTag"))
bean = new Bean();
}
public void endElement(
String uri,
String localName,
String qName) {
value = buffer.toString();
buffer.setLength(0);
if(localName.equals("myTag") {
bean.setSomething(value);
}
}
public void characters(char[] ch, int start, int end) {
buffer.append(new String(ch, start, end));
}
Hope this helps. :)
EDIT
Here the code adapted to the op xml. I haven't tried it but SHOULD work. ;)
private String value;
private StringBuffer buffer;
private XMLCOllected info;
private boolean inPriceList;
private boolean inGold;
private boolean inSilver;
#Override
public void startElement(
String nameSpaceURI,
String localName,
String qName,
Attributes atts
) {
buffer = new StringBuffer();
if(localName.equals("prices")) {
this.info = new XMLCollected();
} else if(localName.equals("pricelist")) {
String attr = atts.getValue("currency");
if(attr.equals("usd")) {
this.inPriceList = true;
}
} else if(localName.equals("price") && inPrices) {
String attr = atts.getValue("commodity");
if(attr.equals("gold")) {
this.inGold = true;
} else if(attr.equals("silver")) {
this.inSilver = true;
}
}
}
public void endElement(
String uri,
String localName,
String qName) {
value = buffer.toString();
buffer.setLength(0);
if(localName.equals("price") && inGold && inPriceList) {
this.info.setSpotGold(value);
this.inGold = false;
} else if(localName.equals("price") && inSilver && inPriceList) {
this.info.setSpotSilver(value);
this.inSilver = false;
} else if(localName.equals("pricelist")) {
this.inPriceList = false;
}
}
public void characters(char[] ch, int start, int end) {
buffer.append(new String(ch, start, end));
}
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 {
}
}