Xml Parsing in android - android

EveryOne I am doing xml parsing like This
public class XMLHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
static ArrayList<Category1> cat_list=new ArrayList<Category1>();
static ArrayList<Products> product_list=new ArrayList<Products>();
Category1 cat;
Products pro;
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_mytag = false;
private boolean in_mytag1 = false;
private boolean in_mytag2 = false;
private boolean in_mytag3 = false;
private XMLDataSet myParsedExampleDataSet = new XMLDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public XMLDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new XMLDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("root")) {
this.in_outertag = true;
}else if (localName.equals("Categories")) {
this.in_innertag = true;
}else if (localName.equals("Category")) {
cat =new Category1();
String attrValue = atts.getValue("id");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
cat.setCatId(i+"");
//cat_id[i]=myParsedExampleDataSet.setExtractedInt(i);
//Log.i("id", cat.setCatId(i+""));
String attrValue1 = atts.getValue("pid");
int i1 = Integer.parseInt(attrValue1);
myParsedExampleDataSet.setExtractedInt(i1);
cat.setPid(i1+"");
//p_id[i1]=myParsedExampleDataSet.setExtractedInt(i1);
//Log.i("pid", myParsedExampleDataSet.setExtractedInt(i1)+"");
this.in_mytag = true;
}else if (localName.equals("title")) {
// Extract an Attribute
this.in_mytag1 = true;
}else if (localName.equals("products")) {
this.in_innertag = true;
}else if (localName.equals("product")) {
pro=new Products();
String attrValue = atts.getValue("catid");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
pro.setCatId(i+"");
//Log.i("catid", myParsedExampleDataSet.setExtractedInt(i)+"");
this.in_mytag = true;
}else if (localName.equals("name")) {
// Extract an Attribute
this.in_mytag2 = true;
}else if (localName.equalsIgnoreCase("url")) {
// Extract an Attribute
this.in_mytag3 = true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("root")) {
this.in_outertag = false;
}else if (localName.equals("Categories")) {
this.in_innertag = false;
}else if (localName.equals("Category")) {
cat_list.add(cat);
this.in_mytag = false;
}else if (localName.equals("title")) {
this.in_mytag1=false;
}else if (localName.equals("products")) {
this.in_innertag=false;
}else if (localName.equals("product")) {
product_list.add(pro);
this.in_mytag=false;
}else if (localName.equals("name")) {
this.in_mytag2=false;
}else if (localName.equalsIgnoreCase("url")) {
this.in_mytag3=false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_mytag1){
myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
cat.setCatName(new String(ch, start, length));
}
if(this.in_mytag2){
myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
pro.setProductId(new String(ch, start, length));
}
if(this.in_mytag3){
String chars = new String(ch, start, length);
chars = chars.trim();
//myParsedExampleDataSet.setExtractedString(chars);
pro.setUrl(chars);
}
}
}
I parse all thing very good but not url....
The Xml file is like this
<?xml version="1.0" encoding="UTF-16"?>
<products>
<product catid="11">
<name>song1</name>
<url>http://news.google.co.in/news?edchanged=1&ned=en_il</url>
</product>
I got the result ned=en_il only
Please Help me, Where i am wrong??
Thankx

You may try by warping your <url> node into CDATA tag like this
<url><![CDATA[http://news.google.co.in/news?edchanged=1&ned=en_il]]></url>
to rectify the issue.

I would recommend using android.sax for parsing it is much easier. You can read about it here http://www.ibm.com/developerworks/opensource/library/x-android/

The problem is likely to be in your characters method.
This method may be called several times for a given element, your code is assuming it will only be called once. e.g. It is likely called for "http://news.google.co.in", "/news?edchanged=1&" and "ned=en_il"
If you append the characters to appropriate properties instead of setting them it will probably work.

Related

parse xml using jsoup

I need parse this xml using Jsoup, XML and i dont know how it works Jsoup. I read the web page jsoup site but i don't understand how to parse.
Need Help, i need to learn how to use it.
I tried parse with simple XML parser but show me this error: Error on line 3, column 10: not well-formed (invalid token).
public class xml4500 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml4500);
TextView tv = (TextView) findViewById(R.id.tv);
try {
URL url = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=4500");
ExampleHandler4500 myExampleHandler = new ExampleHandler4500();
Xml.parse(url.openStream(), Xml.Encoding.UTF_8, myExampleHandler);
List<ParsedExampleDataSet4500> parsedExampleDataSetList =
myExampleHandler.getParsedData();
for(ParsedExampleDataSet4500 parsedExampleDataSet : parsedExampleDataSetList){
tv.append(parsedExampleDataSet.toString());
}
} catch(Exception e){
tv.setText("Error:" + e.getMessage());
}
}
}
Handler
public class ExampleHandler4500 extends DefaultHandler{
private boolean in_indices = false;
private boolean in_fecha = false;
private boolean in_indice = false;
private boolean in_encabezado = false;
private boolean in_columna = false;
private boolean in_titulo = false;
private boolean in_datos = false;
private boolean in_fila = false;
private StringBuilder mStringBuilder = new StringBuilder();
private ParsedExampleDataSet4500 mParsedExampleDataSet = new ParsedExampleDataSet4500();
private List<ParsedExampleDataSet4500> mParsedDataSetList = new ArrayList<ParsedExampleDataSet4500>();
public List<ParsedExampleDataSet4500> getParsedData(){
return this.mParsedDataSetList;
}
#Override
public void startDocument() throws SAXException {
this.mParsedExampleDataSet = new ParsedExampleDataSet4500();
}
#Override
public void endDocument() throws SAXException {
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("indices")){
this.in_indices = true;
}else if(localName.equals("fecha")){
this.in_fecha = true;
}else if(localName.equals("indice")){
this.in_indice = true;
String attrValue1 = attributes.getValue("nombre");
String nombre = String.valueOf(attrValue1);
mParsedExampleDataSet.setNombre(nombre);
}else if(localName.equals("encabezado")){
this.in_encabezado = true;
}else if(localName.equals("columna")){
this.in_columna = true;
}else if(localName.equals("titulo")){
this.in_titulo = true;
}else if(localName.equals("datos")){
this.in_datos = true;
}else if(localName.equals("fila")){
this.in_fila = true;
this.mParsedExampleDataSet = new ParsedExampleDataSet4500();
}
mStringBuilder.setLength(0);
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equals("indices")){
this.mParsedDataSetList.add(mParsedExampleDataSet);
}else if(localName.equals("fecha")){
this.in_fecha = false ;
}else if(localName.equals("indice")){
this.in_indice = false;
}else if(localName.equals("encabezado")){
this.in_encabezado = false;
}else if(localName.equals("columna")){
this.in_columna = false;
}else if(localName.equals("titulo")){
this.in_titulo = false;
}else if(localName.equals("datos")){
this.in_datos = false;
}else if(localName.equals("fila")){
this.in_fila = false;
}
mStringBuilder.setLength(0);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
mStringBuilder.append(ch, start, length);
if(this.in_indices){
mParsedExampleDataSet.setIndices(new String(ch, start, length));
}else if(this.in_fecha){
mParsedExampleDataSet.setFecha(new String(ch, start, length));
}else if(this.in_indice){
mParsedExampleDataSet.setIndice(new String(ch, start, length));
}else if(this.in_encabezado){
mParsedExampleDataSet.setEncabezado(new String(ch, start, length));
}else if(this.in_columna){
mParsedExampleDataSet.setColumna(new String(ch, start, length));
}else if(this.in_titulo){
mParsedExampleDataSet.setTitulo(new String(ch, start, length));
}else if(this.in_datos){
mParsedExampleDataSet.setDatos(new String(ch, start, length));
}else if(this.in_fila){
mParsedExampleDataSet.setFila(new String(ch, start, length));
}
}
Not shure what you want to do with the XML, but parsing it with Jsoup is not a big problem:
// Parse the the website - further connection settings possible here
Document doc = Jsoup.connect("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=4500").get();
// Example - select the (first) 'fecha' tag
Element fecha = doc.select("fecha").first();
// Example - select all 'columna' tags and insert an attribute 'an' with value 'example'
Elements columna = doc.select("columna");
columna.attr("an", "example");
If you have the xml local as a file you can use Document doc = Jsoup.parse(file, "utf-8"); instead of Jsoup.connect(...) (make shure you set proper encoding).
Note: Jsoup Document != DOM Document - however its capable of doing everything you want to do with XML / HTML

Using SAXparser to get info to more than one element (Android)

I'm new in Android (and in Java too) but now I'm starting to work with web services.
So to understand better how to parse an XML, I started to try this tutorial:
http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html
With the XML used in this example:
<outertag>
<innertag sampleattribute="innertagAttribute">
<mytag>anddev.org rulez =)</mytag>
<tagwithnumber thenumber="1337"/>
</innertag>
</outertag>
I understand how it works (I guess), but if the XML is like this:
<outertag>
<innertag sampleattribute="innertagAttribute">
<mytag>anddev.org rulez =)</mytag>
<tagwithnumber thenumber="1337"/>
</innertag>
<innertag sampleattribute="innertagAttribute2">
<mytag>something</mytag>
<tagwithnumber thenumber="14214"/>
</innertag>
</outertag>
What needs to change in the classes of the application to obtain the data of the various elements?
I appreciate any sugestion...
Full source code:
ParseXML.java
package org.anddev.android.parsingxml;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ParsingXML extends Activity {
private final String MY_DEBUG_TAG = "WeatherForcaster";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet =
myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(parsedExampleDataSet.toString());
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
}
/* Display the TextView. */
this.setContentView(tv);
}
}
ExampleHandler
package org.anddev.android.parsingxml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_mytag = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = true;
}else if (localName.equals("innertag")) {
this.in_innertag = true;
}else if (localName.equals("mytag")) {
this.in_mytag = true;
}else if (localName.equals("tagwithnumber")) {
// Extract an Attribute
String attrValue = atts.getValue("thenumber");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = false;
}else if (localName.equals("innertag")) {
this.in_innertag = false;
}else if (localName.equals("mytag")) {
this.in_mytag = false;
}else if (localName.equals("tagwithnumber")) {
// Nothing to do here
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_mytag){
myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
}
}
}
ParsedExampleDataSet
package org.anddev.android.parsingxml;
public class ParsedExampleDataSet {
private String extractedString = null;
private int extractedInt = 0;
public String getExtractedString() {
return extractedString;
}
public void setExtractedString(String extractedString) {
this.extractedString = extractedString;
}
public int getExtractedInt() {
return extractedInt;
}
public void setExtractedInt(int extractedInt) {
this.extractedInt = extractedInt;
}
public String toString(){
return "ExtractedString = " + this.extractedString
+ "nExtractedInt = " + this.extractedInt;
}
}
Problem solved!
Bellow are the sites with useful information:
https://stackoverflow.com/a/4828765
https://stackoverflow.com/a/5709544
http://as400samplecode.blogspot.com/2011/11/android-parse-xml-file-example-using.html
http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html
My initial problem was how I should define the class for the data which I wanted to extract from XML. After I figured out how I should do this (reviewing the basic concepts of JAVA programming), I changed the type of data returned by the ExampleHandler to an ArrayList<"class of the data you want return">.
I give below an example:
Example of a XML you want to parse:
<outertag>
<cartag type="Audi">
<itemtag name="model">A4</itemtag>
<itemtag name="color">Black</itemtag>
<itemtag name="year">2005</itemtag>
</cartag>
<cartag type="Honda">
<itemtag name="model">Civic</itemtag>
<itemtag name="color">Red</itemtag>
<itemtag name="year">2001</itemtag>
</cartag>
<cartag type="Seat">
<itemtag name="model">Leon</itemtag>
<itemtag name="color">White</itemtag>
<itemtag name="year">2009</itemtag>
</cartag>
</outertag>
So here you should define a class "car" with proper attributes (String type, model, color, year;), setters and getters...
My suggestion of ExampleHandler for this XML is:
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private int numberOfItems=3;
private boolean in_outertag = false;
private boolean in_cartag = false;
private boolean[] in_itemtag = new boolean[numberOfItems];
Car newCar = new Car();
private ArrayList<Car> list = new ArrayList<Car>();
// ===========================================================
// Getter & Setter
// ===========================================================
public ArrayList<Car> getParsedData() {
return this.list;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.list = new ArrayList<Car>();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = true;
}else if (localName.equals("cartag")) {
this.in_cartag = true;
newCar.setType(atts.getValue("type")); //setType(...) is the setter defined in car class
}else if (localName.equals("itemtag")) {
if((atts.getValue("name")).equals("model")){
this.in_itemtag[0] = true;
}else if((atts.getValue("name")).equals("color")){
this.in_itemtag[1] = true;
}else if((atts.getValue("name")).equals("year")){
this.in_itemtag[2] = true;
}
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = false;
}else if (localName.equals("cartag")) {
this.in_cartag = false;
Car carTemp = new Car();
carTemp.copy(newCar, carTemp); //this method is defined on car class, and is used to copy the
//properties of the car to another Object car to be added to the list
list.add(carTemp);
}else if (localName.equals("itemtag")){
if(in_itemtag[0]){
this.in_itemtag[0] = false;
}else if(in_itemtag[1]){
this.in_itemtag[1] = false;
}else if(in_itemtag[2]){
this.in_itemtag[2] = false;
}
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(in_itemtag[0]){
newCar.setModel(new String(ch, start, length));
}else if(in_itemtag[1]){
newCar.setColor(new String(ch, start, length));
}else if(in_itemtag[2]){
newCar.setYear(new String(ch, start, length));
}
}
}
After this, you can get the parsed data in the Activity using:
...
ArrayList<Car> ParsedData = myExampleHandler.getParsedData();
...
I hope this helps someone.
Attention: I don't have tested exactly like this, but is almost the same of my solution so it should work...
And sorry for my bad English...

parsing huge length string using sax parser in android

I parsing the xml using sax parser in android. My xml structure is as given below
<customerlist>
<Customer>
<customerId>2</customerId>
<customerFname>prabhu</customerFname>
<customerLname>kumar</customerLname>
<customerImage>
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
</customerImage>
</Customer>
</customerlist>
I am able to get customerId, customerFname, customrLname, but for customerImage I am not getting complete string I am only getting part of the string i.e (iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABHNCSVQICAgIfAhkiAAACJ9JREFUaIHtmllsXFcZx3/n3Due8XgcO3a8xG72tGkTknRJG7qAaEtbhFjVJUpBoBahgkoRUCFe+lCJvkAKCGgFPJQK0VKWqIhShMhL0mahLU1ImjZp0ziZLN5dezxje5Z7z/l4uDOOl9mcOskLf+vTle79fM63nPM/53xn4P+4tFDzrDffkEoKpQxTgAZcoCYvzpT3FxKWwHAD5PLiT3k/DW6JRjQQAupuuadx/VWbYk9b5dcg+uJkQlnR4uaOvjn28J7ticPAOOARODVdtUQTYaDu+7/86GONLfqbvvUiF9DcknB1KJMYtL/a9shrTxA4kWNGFkploAaoa1+t7mxfWhcRqTgULwiUUpG+02N3Aj8jyEBupk4xBxRBBmLJVEqiEznEWgBEBI8MYVVbdHYpFEZ8tNIUT65CrAEFSjmAxZcsIRUp3p7WJFNZAWJAOi/+VJ1SE9IBQmKsgwGsAgth3cCVTZ9FRIFViBXESjC9rCKTG+MjLfcRdRZjJ7+d0/P8LEsab6YxshxjfMK6gU9f/hS+tfk+ZogBMdYhmI8FEpmGcpO4xs8pba1grQCWzcsfYVH0ckbHexkcP8K1nV+jNbaWfad+zliml8+seYpoaCEnh3ZzZfMXuKzhBg50P8v69nuJ1SzmpSPfwPiGnJ+jM7aZtW1fpCW6FusJ6Nk50Br8nNIEQ7posEtlQEGet0QQEayxdMQ2se/U06xsvh3P5NjQvpUzI6+zsul2Wus3MjT+PuO5IXybZVnjzYxMxLFiibhNdCf307HgBqI1bcTcdm5c+m26R/fjKBfBTvYzU+wMm+bkQDaXYiKTJJ1JIlaTM0lWNt7GFc2fIuZ2MJB6l8M9L+JZD7GKkx/sYTDVRSY7Qcab4N8nf01qYpDB1HFOD7+OlhqyuVE8P4OIomvwFTw/O9nHTJnIJMnmUlNtqnoIAbChfQurlrVj
)
My xmlHandler code is below
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.bvbi.invoicing.client.android.customer.model.CustomerPojoInList;
public class CustomerListParser extends DefaultHandler {
Boolean currentElement = false;
String tempValue = null;
CustomerPojoInList customer = null;
public static ArrayList<CustomerPojoInList> customers = null;
#Override
public void startDocument() throws SAXException {
customers = new ArrayList<CustomerPojoInList>();
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("Customer"))
{
/** Start */
customer = new CustomerPojoInList();
}
}
/** Called when tag closing */
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
String currentValue = tempValue;
tempValue = "";
/** set value */
if (localName.equalsIgnoreCase("customerId"))
customer.setCustomerId(currentValue.toString());
else if (localName.equalsIgnoreCase("customerFname"))
customer.setCustomerFname(currentValue.toString());
else if (localName.equalsIgnoreCase("customerLname"))
customer.setCustomerLname(currentValue.toString());
else if (localName.equalsIgnoreCase("customerImage"))
{
Log.d("prabhu","Customer image in parser......"+currentValue);
customer.setCustomerImage(currentValue.toString());
}
else if (localName.equalsIgnoreCase("Customer"))
customers.add(customer);
}
/** Called to get tag characters */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
tempValue = new String(ch,start, length);
if(tempValue.equals(null))
tempValue = "";
currentElement = false;
}
}
#Override
public void endDocument() throws SAXException {
}
}
Please help me to fix the issue.
In sax parser, characters() method parses only maximum of 1024 characters each time. So we need to append the strings until all the characters are parsed.
I changed the above code as follows
public void characters(char[] ch, int start, int length)
throws SAXException
{
Log.d("prabhu","Customer image length in parser......"+length);
if (currentElement ) {
tempValue = new String(ch,start, length);
if(tempValue.equals(null))
tempValue = "";
}
tempValue = tempValue+new String(ch,start, length);
}
The output you posted is exactly 1024 characters. This looks like a certain buffer size. How do you get this output? Maybe check that method and / or your CustomerPojoInList.
I very much believe, that there is some buffer involved that has a maximum of 1024 characters...
Good luck!
first time post. Updated answer with something that might help others. I hope it is not too specific to my particular problem. I am parsing an RSS feed that I create myself with a really long description but the other tags you are interested in, i.e. feed title, date and URL are always short. The description contains information about social events. Within the description, I use tags that I later parse to give me information about the event such as event date (different from RSS pubDate), (Location), (ticketDetails), (Phone), etc, you get the idea.
A good way to handle this is with a slight modification of the answer in this post. I added tags to the description for (Event) and (EndEvent) and I keep appending to my String Builder until I get "(EndEvent)". That way i know i have the full string. It might not work for your situation if you dont control the feed unless you know there is always a certain string at the end of your RSS description.
Posting in case this (cough, hack) helps anyone. Code is as follows:
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
strBuilder = new StringBuilder();
if ("item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("link".equals(qName)) {
parsingLink = true;
}
else if ("pubDate".equals(qName)) {
parsingDate = true;
}
else if ("description".equals(qName)) {
strBuilder = new StringBuilder(); //reset the strBuilder variable to null
parsingDescription = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String descriptionTester = strBuilder.toString();
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
} else if ("link".equals(qName)) {
parsingLink = false;
}
else if ("pubDate".equals(qName)) {
parsingDate = false;
}
//else
// currentItem.setDescription(descriptionTester);
else if ("description".equals(qName) && descriptionTester.contains("(EndEvent)")) {
parsingDescription = false;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (strBuilder != null) {
for (int i=start; i<start+length; i++) {
strBuilder.append(ch[i]);
}
}
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
parsingTitle = false;
}
else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
else if (parsingDate) {
if (currentItem != null) {
currentItem.setDate(new String(ch, start, length));
parsingDate = false;
}
}
else if (parsingDescription) {
if (currentItem != null && strBuilder.toString().contains("(EndEvent)" )) {
String descriptionTester = strBuilder.toString();
currentItem.setDescription(descriptionTester);
parsingDescription = false;
}
}
}
As I said, hope that helps someone as I was stumped on this for a while!

Show null value in the emmulator after Parsing the tag through sax parser in android?

I am making an small application in android of webservices through Sax parser my link is
(http://www.anddev.org/images/tut/basic/parsingxml/example.xml)I am able to display the value of ****<**innertag>,******But can't able to display the value of in theTextView
Here is my sorcs code
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_mytag = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = true;
}else if (localName.equals("innertag")) {
//this.in_innertag = true;
String attrValue = atts.getValue("sampleattribute");
myParsedExampleDataSet.setExtractedString(attrValue);
}else if (localName.equals("mytag")) {
//this.in_mytag = true;
String attrValue = atts.getValue("mytag");
myParsedExampleDataSet.setExtractedString1(attrValue);
}else if (localName.equals("tagwithnumber")) {
// Extract an Attribute
String attrValue = atts.getValue("thenumber");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = false;
}else if (localName.equals("innertag")) {
// this.in_innertag = false;
}else if (localName.equals("mytag")) {
//this.in_mytag = false;
}else if (localName.equals("tagwithnumber")) {
// Nothing to do here
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_mytag){
myParsedExampleDataSet.setExtractedString1(new String(ch, start, length));
}
}
}![enter image description here][1]
You have this.in_mytag = true commented out in startElement(). Therefore the code block in the characters() function that sets ExtractedString1 isn't executing because in_mytag is false.
One other thing when handling the start of mytag: String attrValue = atts.getValue("mytag"); is unnecessary. It should be handled in the characters() function (I suspect you simply had it for debugging purposes).

selecting specific xml tags with SAX parser

I'm designing an App for android and I need to parse an XML file, I've been told SAX parsers are better for mobile devices to I've been trying to use it but I've gotten stuck. Here is the XML code:
<current_conditions>
<condition data="Clear"/>
<temp_f data="50"/>
<temp_c data="10"/>
<humidity data="Humidity: 76%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="Wind: NE at 14 mph"/>
</current_conditions>
<forecast_conditions>
<day_of_week data="Tue"/> ****
<low data="43"/>
<high data="64"/> ****
<icon data="/ig/images/weather/mostly_sunny.gif"/>
<condition data="Mostly Sunny"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="Wed"/>
<low data="43"/>
<high data="64"/>
<icon data="/ig/images/weather/sunny.gif"/>
<condition data="Clear"/>
</forecast_conditions>
I am trying to get values of only the two tags with * by the side but it returns the values at the end of the document instead. How do I solve this problem as I only want certain values in the XML. Here is my code:
public class ExampleHandler extends DefaultHandler {
private boolean in_in_current_conditions = false;
private boolean in_in_forecast_conditions = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
}
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException
{
if (localName.equals("forecast_information"))
{
this.in_forecast_information = true;
}
else if (localName.equals("current_conditions"))
{
this.in_in_current_conditions = true;
}
else if (localName.equals("forecast_conditions"))
{
this.in_in_forecast_conditions = true;
}
else if (localName.equals("high")) {
if (this.in_in_forecast_conditions)
{
String attrValue = atts.getValue("data");
myParsedExampleDataSet.setCurrtempValue(attrValue);
}
} else if (localName.equals("day_of_week")) {
if (this.in_in_forecast_conditions) {
String attrValue1 = atts.getValue("data");
myParsedExampleDataSet.setLowValue(attrValue1);
}
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("forecast_information")) {
this.in_forecast_information = false;
} else if (localName.equals("current_conditions")) {
this.in_in_current_conditions = false;
} else if (localName.equals("forecast_conditions")) {
this.in_in_forecast_conditions = false;
}
}
#Override
public void characters(char ch[], int start, int length) {
}
}
If I were you then I would just use the Simple XML framework to do the XML parsing work for you. It would not be too difficult then to just create a few objects that could tease this data out of the XML.
P.S. I use the Simple project for all my XML so I even wrote a blog post explaining how to use it in Android projects: you can read it here.
To get those two values you would do something like this:
public class ExampleHandler extends DefaultHandler {
private static final String FORECAST_CONDITION = "forecast_condition";
private boolean day_of_week_dataWanted = false;
private boolean high_dataWanted = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
public ExampleHandler() {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if(FORECAST_CONDITION.equals(localName)){
if("day_of_week".equals(localName)){
day_of_week_dataWanted = true;
}
if("high".equals(localName)){
high_dataWanted = true;
}
}
}
#Override
public void characters(char ch[], int start, int length) {
if(day_of_week_dataWanted){
myParsedExampleDataSet.setLowValue(new String(ch, start, length));
day_of_week_dataWanted = false;
}
if(high_dataWanted){
myParsedExampleDataSet.setCurrtempValue(new String(ch, start, length));
high_dataWanted = false;
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
}
}
But there are more graceful solutions you could look at, hopefully this gives you a hint.
I've sorted this by using populating the values in Arrays and when I want to display them I simple use their position in the array to call them

Categories

Resources