I have a problem when parsing xml from the internet. The parser doesn't return all the data correctly.
Three are three errors:
correct result -->return result
161:1:161-->1:1:161
330:2:132-->3:2:132
421:2:223-->4:2:223
Copy of the xml file I am trying to parse
https://docs.google.com/open?id=0BwXEx9yI14inT1BnR2xzYnJEX0E
Activity
public class DataBaseUpdateService_1 extends Activity {
private TextView TextView1 ;
private LinearLayout linearlayout1 ;
private TextView title[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_item);
linearlayout1 = (LinearLayout)findViewById(R.id.linearlayout1);
TextView1 = (TextView)findViewById(R.id.textView1);
MyDBHelper dbHelper =new MyDBHelper(DataBaseUpdateService_1.this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://123.com/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
DataBaseUpdate_XMLHandler XMLHandler = new DataBaseUpdate_XMLHandler();
xr.setContentHandler(XMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
int itemCount = DataBaseUpdate_XMLHandler.array.size();
db.delete("hymns_match", null, null);
try{
for(int i=0;i<itemCount;i++) {
String songs_id=DataBaseUpdate_XMLHandler.array.get(i).get("songs_id");
String songs_book_id=DataBaseUpdate_XMLHandler.array.get(i).get("songs_book_id");
String songs_book_ch=DataBaseUpdate_XMLHandler.array.get(i).get("songs_book_ch");
TextView tv = new TextView(DataBaseUpdateService_1.this);
tv.setText(songs_id + ":"+songs_book_id+ ":"+songs_book_ch);
linearlayout1.addView(tv);
}
}catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
DataBaseUpdate_XMLHandler
public class DataBaseUpdate_XMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue=null;
static ArrayList<LinkedHashMap<String, String>> array;
LinkedHashMap map;
#Override
public void startDocument() throws SAXException {
array = new ArrayList<LinkedHashMap<String, String>>();
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("song")) {
map = new LinkedHashMap<String, Object>();
currentValue=null;
}
/*Get attribute
* else if (localName.equals("website")) {
* String attr = attributes.getValue("category");
* sitesList.setCategory(attr);}
* */
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("songs_id")){
map.put("songs_id",currentValue);}
else if (localName.equalsIgnoreCase("songs_book_id")){
map.put("songs_book_id", currentValue);}
else if (localName.equalsIgnoreCase("songs_book_ch")){
map.put("songs_book_ch", currentValue);}
else if (localName.equalsIgnoreCase("song")){
array.add(map);}
}
/** Called to get tag characters
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
Can you give some advice about what's wrong here?
According to the SAX definition characters() method can be called multiple times per elements. So it should accumulate the text; if this is happening then your code will not work.
Related
hello friends i have one spinner adapter which contain data from web service and i fill on it as follow
Main.Java
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://www.findyourfate.com/rss/yearly-horoscope.asp?sign=Leo"); // URL of the XML
System.out.println("URL Y "+url);
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
data = XMLHandler.data;
mTextViewDate.setText("Date : "+ data.getTitle());
mTextViewDesc.setText(data.getDescription());
System.out.println("data.getDescription() "+data.getDescription());
**XMLGettersSetters.java **
public class XMLGettersSetters {
String title="";
String description="" ;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
XMLHandler.java
public class XMLHandler 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) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("channel"))
{
data = new XMLGettersSetters();
} else if (localName.equals("item")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
}
}
/**
* 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("title"))
data.setTitle(elementValue);
else if (localName.equalsIgnoreCase("description"))
data.setDescription(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;
}
}
}
when i run above code it give description only GENERAL . other text is not getting so any idea how can i solve it ?
#Override
public String toString() {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
sb.append(title);
sb.append('\n');
sb.append(pubdate);
sb.append(link);
sb.append('\n');
sb.append(description);
sb.append('\n');
return sb.toString().toignorecase();
}
try to add this Line in your **XMLGettersSetters.java **
I am making an application for Android and I need to display an XML file of this page:http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009
I tried the solutions given on the page but I find it wrong since it is not displayed when you run the application. I just want to show "tipo= DOLAR SPOT INTERCAMBIO"
This is the XML CODE
and this is my code:
xmlpruebaprueba.jar
XMLdataCollected sitesList= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlpruebaprueba);
//creando un Layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
//creando TextView
TextView Registro[];
TextView Tipo[];
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceURL = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009");
handlingXml HandlingXml = new handlingXml();
xr.setContentHandler(HandlingXml);
xr.parse(new InputSource(sourceURL.openStream()));
}catch (Exception e){
System.out.println("XML Parsing Exception= " + e);
}
sitesList = handlingXml.sitesList;
Registro = new TextView[sitesList.getRegistro().size()];
Tipo = new TextView[sitesList.getTipo().size()];
for (int i = 0; i < sitesList.getRegistro().size(); i++) {
Registro[i] = new TextView(this);
Registro[i].setText("Registro = "+sitesList.getRegistro().get(i));
Tipo[i] = new TextView(this);
Tipo[i].setText("Tipo = "+sitesList.getTipo().get(i));
layout.addView(Registro[i]);
layout.addView(Tipo[i]);
}
}
}
and this is my handler
Boolean currentElement = false;
String currentValue = null;
public static XMLdataCollected sitesList = null;
public static XMLdataCollected getDataCollected (){
return sitesList;
}
public static void setSitesList(XMLdataCollected sitesList){
handlingXml.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
currentElement = true;
if(localName.equals("Root"))
{
sitesList = new XMLdataCollected();
}else if (localName.equals("Registro")){
String attr = attributes.getValue("tipo");
sitesList.setTipo(attr);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
currentElement = false;
if (localName.equalsIgnoreCase("Registro"))
sitesList.setRegistro(currentValue);
else if (localName.equalsIgnoreCase("Root"))
sitesList.setRoot(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
and this is my dataCollected
public class XMLdataCollected {
private ArrayList<String> root = new ArrayList<String>();
private ArrayList<String> registro = new ArrayList<String>();
private ArrayList<String> tipo = new ArrayList<String>();
public ArrayList<String> getRoot (){
return root;
}
public void setRoot(String root){
this.root.add(root);
}
public ArrayList<String> getRegistro (){
return registro;
}
public void setRegistro(String registro){
this.registro.add(registro);
}
public ArrayList<String> getTipo (){
return tipo;
}
public void setTipo(String tipo){
this.tipo.add(tipo);
}
}
You are calling your Web Request on main UI thread.
PLEASE DO NOT DO THIS
use AsyncTask to call web your request.
i parse the xml file and all data will parsed but i dont understand how to set this data in textview ? give me some idea about that
public class GtuItemXMLHandler extends DefaultHandler {
Gtudownload gtudownload;
Questionpaper questionpaper;
// Show me the XML.
private String currentString = "";
private String charactersString = "";
private Branch branch;
private Year year;
private Semester semester;
private int branchCount = 0;
private int yearCount = 0;
private int semesterCount = 0;
// private ArrayList<Gtudownload> itemsList = new ArrayList<Gtudownload>();
//
// public ArrayList<Gtudownload> getItemsList() {
// return itemsList;
// }
public Gtudownload getGtudownload(){
return this.gtudownload;
}
public Questionpaper getQuestionpaper()
{
return this.questionpaper;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i("GTU ", localName);
if (localName.equalsIgnoreCase("Gtudownload")) {
gtudownload = new Gtudownload();
currentString = "Gtudownload";
} else if (localName.equalsIgnoreCase("Questionpaper")) {
gtudownload.setQuestionpaper(new Questionpaper());
gtudownload.getQuestionpaper().setBranchList(new ArrayList<Branch>());
currentString = "Questionpaper";
} else if (localName.equalsIgnoreCase("Branch")) {
branch = new Branch();
gtudownload.getQuestionpaper().getBranchList().add(branch);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).setYearList(new ArrayList<Year>());
currentString = "Branch";
Log.i("Branch", attributes.getValue("value"));
branch.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("Year")) {
year = new Year();
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().add(year);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).setSemesterList(new ArrayList<Semester>());
currentString = "Year";
Log.i("Year ", attributes.getValue("value"));
year.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("semester")) {
semester = new Semester();
currentString = "semester";
Log.i("Semester ", attributes.getValue("value"));
semester.setValue(attributes.getValue("value"));
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().add(semester);
} else if (localName.equalsIgnoreCase("url")){
currentString = "url";
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("Questionpaper")){
branchCount=0;
}else if(localName.equalsIgnoreCase("Branch")){
yearCount = 0;
branchCount++;
}else if(localName.equalsIgnoreCase("Year")){
semesterCount = 0;
yearCount++;
}else if(localName.equalsIgnoreCase("semester")){
semesterCount++;
}else if(localName.equalsIgnoreCase("url")){
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().get(semesterCount).setUrl(charactersString);
Log.i("URL", charactersString);
}
currentString = "";
charactersString= "";
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
charactersString = new String(ch, start, length);
charactersString = charactersString.trim();
}
}
this is my activity and how can i set this parsing data in into textview
public class GtudldActivity extends Activity {
/** Called when the activity is first created. */
private TextView xmlOutput;
TextView example[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
xmlOutput = (TextView) findViewById(R.id.xmlOutput);
Gtudownload gtudownload = parseXML();
}
private Gtudownload parseXML() {
Gtudownload gtudownload = null;
try {
Log.w("AndroidParseXMLActivity", "Start");
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
GtuItemXMLHandler myXMLHandler = new GtuItemXMLHandler();
xr.setContentHandler(myXMLHandler);
InputSource is = new InputSource(getResources().openRawResource(R.raw.mgtu));
gtudownload = myXMLHandler.getGtudownload();
Log.i("Data",gtudownload+"");
xr.parse(is);
} catch (Exception e) {
Log.w("AndroidParseXMLActivity", e);
}
//xmlOutput.setText(gtudownload.toString());
return gtudownload;
}
}
You'll get so many examples for this on google. I am showing you one of the. Just try this
I hope it may help you. If you've any doubt, just post it here
I retrieve XML from a server, save it into an SD card, then parse that XML. I get this exception:
03-19 13:53:26.943: E/AndroidRuntime(12512): FATAL EXCEPTION: main
03-19 13:53:26.943: E/AndroidRuntime(12512): java.lang.NullPointerException.
I am using this code:
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadFromUrl("http://www.androidpeople.com/wp- content/uploads/2010/06/example.xml","example.xml");
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
String path = Environment.getExternalStorageDirectory() +"../xmls"+"/example.xml";
File file = new File(path);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
DataHandler myXMLHandler = new DataHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));//parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from DataHandler SitlesList Object */
sitesList = DataHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getWebsite().size()];
category = new TextView[sitesList.getCategory().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
private void DownloadFromUrl(String DownloadUrl, String fileName)
{
URL url;
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
try {
url = new URL(DownloadUrl);
File file = new File(dir, fileName);
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
//Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //you can write here any link
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And my handler class is :
Boolean currentElement = false;
Context theContext;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList()
{
return sitesList;
}
public static void setSitesList(SitesList sitesList)
{
DataHandler.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
super.startElement(uri, localName, qName, attributes);
currentElement = true;
if (localName.equals("maintag"))
{
/** Start */
sitesList = new SitesList();
}
else if (localName.equals("website"))
{
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
else if (localName.equalsIgnoreCase("website"))
sitesList.setWebsite(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if (currentElement)
{
currentValue = new String(ch, start, length);
currentElement = false;
}
}
And my list class is:
/** Variables */
private ArrayList name = new ArrayList();
private ArrayList website = new ArrayList();
private ArrayList category = new ArrayList();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
public ArrayList getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList getCategory() {
return category;
}
public void setCategory(String category) {
this.category.add(category);
}
The XML file is downloaded and saved into the SD card properly but not parsed.
SAX (Simple API for XML) is an event-based sequential access parser API developed by the XML-DEV mailing list for XML documents. SAX provides a mechanism for reading data from an XML document that is an alternative to that provided by the Document Object Model (DOM). Where the DOM operates on the document as a whole, SAX parsers operate on each piece of the XML document sequentially
Please refer this link for your solution.
It will help you.
I have a XML file in assets folder.
I am parsing it in my Activity and displaying it.
In XML file I has a data with < symbol, I use < at < symbol.
But, the symbol is not displying and text after the symbol only i am getting.
ex "hi < hello"
parsing result will be only hello
parsing code
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
SecondHandler shandler = new SecondHandler();
xr.setContentHandler(shandler);
InputStream in = this.getAssets().open(fileName);
xr.parse(new InputSource(in));
itemlist = shandler.getParsedData();
} catch (Exception e) {
System.out.println("Error : " + e);
}
Map<String, String> item = (Map<String, String>) list.get(5);
String qus = item.get("question");
String ans = item.get("answer");
}
xml file..
..........
<dict>
<question>hello</question>
<answer>I am < 5 you</answer>
</dict>
......
handler code.
public class SecondHandler extends DefaultHandler {
private String tagName;
#SuppressWarnings("rawtypes")
private ArrayList<Map> dataSet;
private Map<String, String> dictionary;
#SuppressWarnings("rawtypes")
public ArrayList<Map> getParsedData() {
return dataSet;
}
#Override
public void startDocument() throws SAXException {
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#SuppressWarnings("rawtypes")
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
tagName = localName;
if (localName.equals("array")) {
this.dataSet = new ArrayList<Map>();
} else if (localName.equals("dict")) {
dictionary = new HashMap<String, String>();
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("array")) {
} else if (localName.equals("dict")) {
dataSet.add(dictionary);
}
}
#Override
public void characters(char ch[], int start, int length) {
String string = new String(ch, start, length);
string = string.replaceAll(" ", "");
string = string.replaceAll("\n", "");
string = string.replaceAll("\t", "");
if (string.length() > 0 && string != null) {
dictionary.put(tagName, new String(ch, start, length));
// System.out.println("Dictionary : " + dictionary);
}
}
}
How to solve this problem
Thanks in advance...!
A SAX parser can supply character data to the ContentHandler in as many calls of the characters() method as it chooses. Your characters() method is putting each of the substrings in the same hashtable entry, overwriting any previous substrings; you need to concatenate them.
may be you directly use "<" in xml file write ,
So use Value-->String class
==>string name="temperature_lt" value is= Temperature & l t;(Note here ignore space)
and extractin xml file
==>android:text="#string/temperature_lt"
try it,