Android: Sax Reader, can't extract information needed - android

I am receiving a response from a XML request and I need to deal with it. The response will return either '00' when the request has been accepted and the account is verified and a '03' when the account is invalid.
Currently the Sax Reader is returning the correct information but I cannot extract the information from the reader so I can store the username / password into the internal storage of the phone.
The code from the Sax Reader is:
public void inputStreamToString(InputStream is) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean errorCode = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("ErrorCode"))
{
errorCode = true;
}
}
public void endElement(String uri, String localName,String qName) throws SAXException
{
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException
{
if (errorCode)
{
System.out.println("ErrorCode : "+ new String(ch, start, length));
if (ch.equals(00))
{
System.out.println("IT WORKS!!!");
}
errorCode = false;
}
}
};
saxParser.parse(is, handler);
}
catch (Exception e)
{
System.out.println("Sax Error");
e.printStackTrace();
}
}
As you can see in the public void characters it is printing out the errorcode that is relevant from the response. I am currently trying to do ch.equals(00) in a If statement but it isn't picking out the correct information! Could it be a problem that ch is a char data type?
Any help will be appreciated.

I got it working. Instead of using '00' and '03' error codes. I have used the length of the response messages which are 'OK' and 'Invalid'.

Related

How to parse xml data using SAX Parser and show it in listview

I want to parse XML data using SAX Parser and show the parsed data in the listview.
The XML is given below:-
<?xml version="1.0" encoding="UTF-8"?>
<category>
<category_info>
<parent_title>Shop</parent_title>
<parent_id>3</parent_id>
<has_more_items>0</has_more_items>
</category_info>
<items>
<item>
<label>Citrus</label>
<entity_id>130</entity_id>
<next>4</next>
<subcategory>0</subcategory>
<content_type>products</content_type>
<parent_id>128</parent_id>
<icon>http://foakh.com/media/catalog/category/cache/11/thumbnail/100x/9df78eab33525d08d6e5fb8d27136e95/yyyy.jpg</icon>
</item>
<item>
<label>Apples</label>
<entity_id>131</entity_id>
<next>3</next>
<subcategory>0</subcategory>
<content_type>products</content_type>
<parent_id>128</parent_id>
<icon>http://foakh.com/media/catalog/category/cache/11/thumbnail/100x/9df78eab33525d08d6e5fb8d27136e95/yyyy.jpg</icon>
</item>
</items>
</category>
I have to pull the data of tag and save it in the list and after that I have to show it in the custom listview. There is a method after_product(product_list) where the data are taken to the activity. Here is the code for parsing XML data but the data are not saved in the listview and as a result data are not displaying in the listview. It is obvious that I have done some mistake but can't figure it out. So can anybody help me out of this.
#Override
public void onSuccess(String response) {
// TODO Auto-generated method stub
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser mSaxParser = factory.newSAXParser();
XMLReader mXmlReader = mSaxParser.getXMLReader();
mXmlReader.setContentHandler(this);
BufferedReader br = new BufferedReader(new StringReader(response));
InputSource is = new InputSource(br);
mXmlReader.parse(is);
} catch (Exception e) {
Log.e("TAG", "Exception: " + e.getMessage());
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
tempval = new String(ch, start, length);
if (b_label == true)
str_label = str_label + tempval;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("items"))
product_list = new ArrayList<Products>();
if (localName.equalsIgnoreCase("item"))
productdto = new Products();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("label")) {
productdto.setLabel(tempval);
str_label = "";
b_label = false;
} else if (localName.equalsIgnoreCase("entity_id"))
productdto.setEntity_id(tempval);
else if (localName.equalsIgnoreCase("next"))
productdto.setNext(tempval);
else if (localName.equalsIgnoreCase("subcategory"))
productdto.setSubcategory(tempval);
else if (localName.equalsIgnoreCase("content_type"))
productdto.setContent_type(tempval);
else if (localName.equalsIgnoreCase("parent_id")) {
if (productdto != null)
productdto.setParent_id(tempval);
}
else if (localName.equalsIgnoreCase("icon"))
productdto.setIcon(tempval);
else if (localName.equalsIgnoreCase("items")) {
((ProductList) mActivity).after_product(product_list);
}
}
The method after_product(product_list) is given below:-
public void after_product(ArrayList<Products> product_list) {
productAdapter = new ProductListItemsAdapter(ProductList.this, 0, product_list);
list_view.setAdapter(productAdapter);
dialog.dismiss();
}
I have got stucked here. Please help me out.
There have some point that you should check out:
XML parse is work well?
If not, make sure XML parse work well.
Is productdto added to the product_list after parsed?
According to your code, I think you should add case in your "endElement" function like this:
else if (localName.equalsIgnoreCase("item"))
product_list.add(productdto);
Make sure "ProductListItemsAdapter" work well.
Hope my answer is helpful for you,sorry about my English is so bad :P

Android SAXParse Get Value Between Tags

I have an XML file I am reading in via SAXParser, but I am having trouble reading it in correctly. The XML is structured like this:
<game>
<players>
<player>
<name>Player 1</name>
<score>100</score>
</player>
</players>
</game>
How can I get the Android SAXParser to read the values between tags? This is the code that I have, but it is looking for an attribute to the tag, not the text between.
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(localName.equals("name")) {
names.add(attributes.getValue("name"));
}
else if(localName.equals("score")) {
scores.add(Integer.parseInt(attributes.getValue("score")));
}
}
Drawing from the example #
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
More info about sax #
http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html
Apart from sax you should have a look at xmllpullparser which is recommended.
Quoting from the docs.
We recommend XmlPullParser, which is an efficient and maintainable way to parse XML on Android.
Check the link #
http://developer.android.com/training/basics/network-ops/xml.html
public void readxml(){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bname = false;
boolean bscore = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("name")) {
bname = true;
}
if (qName.equalsIgnoreCase("score")) {
bscore = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bname) {
Toast.makeText(getApplicationContext(), new String(ch, start, length), 10000).show();
bname = false;
}
if (bscore) {
Toast.makeText(getApplicationContext(), new String(ch, start, length), 10000).show();
bscore = false;
}
}
};
saxParser.parse("myxmltoparse", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Issue while reading from XML file on sdcard

Friends, I am facing an issue while reading information from a xml file located on the SD card.The code is being implemented successfully but there is nothing being displayed either on logcat nor there is no exception popping out. Please help me for the same.
public class History extends Activity
{
private ListView lstv;
static ArrayList<Records> arr;
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
setContentView(R.layout.history);
try {
String path = Environment.getExternalStorageDirectory()+"/saved_images/history.xml";
File file = new File(path);
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
XMLHandler handler=new XMLHandler();
//parser.parse(stream,handler);
reader.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));
arr=handler.getArray();
ArrayAdapter<Records> adpt=new ArrayAdapter<Records>(this, android.R.layout.simple_list_item_1,arr);
//lstv.setAdapter(adpt);
handler.startDocument();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class XMLHandler extends DefaultHandler {
ArrayList<Records> array;
Records records ;
String strCurrentValue = null;
public ArrayList<Records> getArray() {
return array;
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
array=new ArrayList<Records>();
}
#Override
public void startElement(String uri, String elementName, String qName,Attributes attributes) throws SAXException {
super.startElement(uri, elementName, qName, attributes);
if(elementName.equals("Record"))
{
records=new Records();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
strCurrentValue=new String(ch, start, length);
}
#Override
public void endElement(String uri, String elementName, String qName)
throws SAXException {
super.endElement(uri, elementName, qName);
if(elementName.equals("date"))
{
records.date=strCurrentValue;
}else if(elementName.equals("cc"))
{
records.cc=strCurrentValue;
}
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
for(Records c:array)
{
Log.d("XmlHandler", c.toString());
}
}
}
}
I am unable to see anything on log-cat or onto the screen. Please help me for the same code using snippets.
Thanks
It seems to me that your handler never actually adds the record to the array - looks like you need to include an action for the endElement of type 'Record' which adds it to the array.
Also as Giovanni says this entire piece of code will hold up the UI thread so if the XML file is non-trivial this should be handled in a separate thread with a progress dialog.

sax parsing: take value from div tag

I am doing an Android application. In my app I have to parse a xml page.The data in the xml page is in the following format.
<root>
<tag1>data</tag1>
<tag2>
<div>data1</div><div>data2</div>
</tag2>
</root>
to tried to take data through sax parsing.
if (localName.equalsIgnoreCase("tag1"))
if (localName.equalsIgnoreCase("tag2"))
But I am not getting any data from tag2 but getting value from tag1.I want to get all data include div tag also then only i can show data in like html page.
Use this sample code
public class SAXParserDemo extends DefaultHandler {
private String currentTag = "";
private StringBuffer responseTag;
private String str;
#Override
public void startDocument() throws SAXException {
super.startDocument();
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
currentTag = localName;
if ("tag1".equalsIgnoreCase(localName)) {
responseTag = new StringBuffer();
}else if ("tag2".equalsIgnoreCase(localName)) {
responseTag = new StringBuffer();
}else if ("div".equalsIgnoreCase(localName)) {
responseTag = new StringBuffer();
}
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
String responseValue = responseTag.toString().trim();
if ("tag1".equalsIgnoreCase(localName)) {
Log.v("TAG", "Tag 1 value "+responseValue);
}else if ("tag2".equalsIgnoreCase(localName)) {
Log.v("TAG", "Tag 2 value "+responseValue);
}else if ("div".equalsIgnoreCase(localName)) {
Log.v("TAG", "div value "+responseValue);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
str = new String(ch, start, length);
if ("tag1".equalsIgnoreCase(currentTag)) {
responseTag.append(str);
}else if ("tag2".equalsIgnoreCase(currentTag)) {
responseTag.append(str);
}else if ("div".equalsIgnoreCase(currentTag)) {
responseTag.append(str);
}
}
}
If you are using SAX parsing, you need to look for the div element and you need to keep track of the parent element (yourself) and make sure that's tag2. You are getting the data (characters) in the tag1 element because it directly contains those characters. The tag2 element does not contain any (non-whitespace) characters, only other elements.

SAXParser encoding

I have a problem with encoding. To begin with perhaps a bit of code:
URL xmlUrl = new URL("http://helion.pl/rss/GW/promocje.rss");
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser parser = saxFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
Helion xmlHandler = new Helion();
reader.setContentHandler(xmlHandler);
InputSource inputSource = new InputSource(xmlUrl.openStream());
inputSource.setEncoding("ISO-8859-1");
reader.parse(inputSource);
The file is encoded ISO-8859-2, but when I use setEncoding("ISO-8859-2") file is not read. Please help.
DefaultHandler:
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTagName = qName;
if (TAG_ITEM.equalsIgnoreCase(qName)) {
odczyt = true;
element = new Element();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String value = new String(ch, start, length);
if (!value.trim().equals("")) {
if (odczyt) {
if (TAG_TYTOL.equalsIgnoreCase(currentTagName)) {
element.setTytol(value);
} else if (TAG_OPIS.equalsIgnoreCase(currentTagName)) {
element.setOpis(value);
}
}
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (TAG_ITEM.equalsIgnoreCase(localName)) {
odczyt = false;
elementy.add(element);
}
}
}
As Francis Upton mentions, characters can be called multiple times within one XML start/end element.
You should do something like this:
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String s = new String(ch, start, length);
if (mTextBuffer == null) {
mTextBuffer = new StringBuffer(s);
} else {
mTextBuffer.append(s);
}
}
And then call element.setTytol(mTextBuffer)/element.setOpis(mTextBuffer) in your endElement method
In your code you are setting it to ISO-8859-1 which is very different, could that be the problem?

Categories

Resources