Parsing an RSS feed cuts of characters - android

I parse some RSS feed (tried with different ones...) and everytime pretty randomly characters get cut of.
What am I doing wrong? Why does it work in some instances and in other ones it doesn't?
Is there another way of doing it? The XML will (in most of the cases) include UTF-8 characters (like ä,ö,ü etc.) so the solution should work with those characters too.
If you need any more information (More code, more detailed information etc.) please let me know!
Here is my Code:
public class RSSHandler extends DefaultHandler {
final int state_unknown = 0;
final int state_title = 1;
final int state_description = 2;
final int state_link = 3;
final int state_pubdate = 4;
int currentState = state_unknown;
StringBuilder strCharacters;
RSSFeed feed;
RSSItem item;
boolean inEntity = false;
String entityName = "";
boolean itemFound = false;
public RSSHandler() {
strCharacters = new StringBuilder();
}
public RSSFeed getFeed() {
return feed;
}
#Override
public void startDocument() throws SAXException {
feed = new RSSFeed();
item = new RSSItem();
}
#Override
public void endDocument() throws SAXException {
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
strCharacters = new StringBuilder();
if (localName.equalsIgnoreCase("item")) {
itemFound = true;
item = new RSSItem();
currentState = state_unknown;
} else if (localName.equalsIgnoreCase("title")) {
currentState = state_title;
} else if (localName.equalsIgnoreCase("description")) {
currentState = state_description;
} else if (localName.equalsIgnoreCase("link")) {
currentState = state_link;
} else if (localName.equalsIgnoreCase("pubdate")) {
currentState = state_pubdate;
} else {
currentState = state_unknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (itemFound == true) {
switch (currentState) {
case state_title:
item.setTitle(strCharacters.toString());
break;
case state_description:
break;
case state_link:
item.setLink(strCharacters.toString());
break;
case state_pubdate:
String dateStr = strCharacters.toString();
SimpleDateFormat curFormater = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
Date dateObj = null;
try {
dateObj = curFormater.parse(dateStr);
SimpleDateFormat postFormater = new SimpleDateFormat(
"dd.MM.yyyy HH:mm");
String newDateStr = postFormater.format(dateObj);
item.setPubdate(newDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
break;
default:
break;
}
} else {
switch (currentState) {
case state_title:
feed.setTitle(strCharacters.toString());
break;
case state_description:
break;
case state_link:
feed.setLink(strCharacters.toString());
break;
case state_pubdate:
feed.setPubdate(strCharacters.toString());
break;
default:
break;
}
}
currentState = state_unknown;
if (localName.equalsIgnoreCase("item")) {
feed.addItem(item);
}
}
public void startEntity(String name) throws SAXException {
inEntity = true;
entityName = name;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
strCharacters = new StringBuilder();
if (inEntity) {
inEntity = false;
strCharacters.append("&" + entityName + ";");
} else {
for (int i = start; i < start + length; i++) {
strCharacters.append(ch[i]);
}
}
// strCharacters.append(ch, start, length);
}
}

You are creating a new StringBuilder on each characters() call. This is incorrect. There many be several calls to characters() per element -- you need to concatenate all those results, not just collect the last piece.

Related

Get images from rss feed

I'm trying to display the images of rss feed with Android Studio but I don't know how to do this. I can get all the other items but I don't know why I can't get the images. Can you help me please?
This is my Handler:
public class RSSHandler extends DefaultHandler {
final int state_unknown = 0;
final int state_title = 1;
final int state_description = 2;
final int state_link = 3;
final int state_pubdate = 4;
final int state_enclosure = 5;
final int state_url = 6;
int currentState = state_unknown;
RSSFeed feed;
RSSItem item;
boolean itemFound = false;
RSSHandler(){
}
RSSFeed getFeed(){
return feed;
}
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
feed = new RSSFeed();
item = new RSSItem();
}
#Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
itemFound = true;
item = new RSSItem();
currentState = state_unknown;
}
else if (localName.equalsIgnoreCase("url")){
currentState = state_url;
}
//{
// if (!attributes.getValue("url").equalsIgnoreCase("null")) {
// feed.setImage(attributes.getValue("url"));
//} else {
// feed.setImage("");
//}
// currentState = state_image;
//}
else if (localName.equalsIgnoreCase("enclosure")){
currentState = state_enclosure;
}
else if (localName.equalsIgnoreCase("title")){
currentState = state_title;
}
else if (localName.equalsIgnoreCase("description")){
currentState = state_description;
}
else if (localName.equalsIgnoreCase("link")){
currentState = state_link;
}
else if (localName.equalsIgnoreCase("pubdate")){
currentState = state_pubdate;
}
else{
currentState = state_unknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
feed.addItem(item);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch,start,length);
if (itemFound==true){
// "item" tag found, it's item's parameter
switch(currentState){
case state_url:
item.setUrl(strCharacters);
break;
case state_enclosure:
item.setEnclosure(strCharacters);
break;
case state_title:
item.setTitle(strCharacters);
break;
case state_description:
item.setDescription(strCharacters);
break;
case state_link:
item.setLink(strCharacters);
break;
case state_pubdate:
item.setPubdate(strCharacters);
break;
default:
break;
}
}
else{
// not "item" tag found, it's feed's parameter
switch(currentState){
case state_url:
feed.setUrl(strCharacters);
break;
case state_enclosure:
feed.setEnclosure(strCharacters);
break;
case state_title:
feed.setTitle(strCharacters);
break;
case state_description:
feed.setDescription(strCharacters);
break;
case state_link:
feed.setLink(strCharacters);
break;
case state_pubdate:
feed.setPubdate(strCharacters);
break;
default:
break;
}
}
currentState = state_unknown;
}
EDIT
how I show images
try {
URL url = new URL(web.get(position).getEnclosure()+web.get(position).getUrl());
HttpGet httpRequest;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
ImageView img = (ImageView) rowView.findViewById(R.id.enclosure);
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
ex.printStackTrace();
}
The code you've posted isn't really relevant to the problem, you should have already fetched the feed and parsed it to extract the urls, you can then do the following, however I would recommend Picasso from Square instead which will do all the heavy lifting AND add functionality like caching and interrupting requests automatically - http://square.github.io/picasso/
try {
InputStream inStream = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(inStream, "my source name");
return d;
} catch (Exception e) {
return null;
}

How to decode a string from xml in android?

In my xml, i have <ns5:Name>mil & carbon</ns5:Name>
From my java code i am retrieving that value by
public class MasterdataParser extends MasterdataBaseParser {
protected MasterdataParser(InputStream response) {
super(response);
}
public MasterData parse() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
MasterData masterData;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
Element root = dom.getDocumentElement();
masterData = new MasterData();
NodeList list;
Element element;
NodeList childNodeList;
Node node;
String nodeName;
list = root.getElementsByTagName(PREFIX+CATEGORY);
for (int i=0;i<list.getLength();i++){
element = (Element) list.item(i);
childNodeList = element.getChildNodes();
Category category = new Category();
for (int j = 0; j < childNodeList.getLength(); j++) {
node = childNodeList.item(j);
nodeName = node.getNodeName();
if (nodeName.equalsIgnoreCase(PREFIX+CATEGORY_ID)) {
try{
category.setId(node.getFirstChild().getNodeValue());
} catch (NullPointerException ex) {
category.setId(null);
}
}
if (nodeName.equalsIgnoreCase(PREFIX+CATEGORY_NAME)) {
try{
// System.out.println("Masterdataparser category name html "+Html.fromHtml(node.getFirstChild().getNodeValue())); // Not worked
System.out.println("URL Decoder "+URLDecoder.decode(node.getFirstChild().getNodeValue(), "UTF-8")); // Not worked
category.setName(node.getFirstChild().getNodeValue());
} catch (NullPointerException ex) {
category.setName(null);
}
}
}
public abstract class MasterdataBaseParser implements MasterdataParserInterface {
static final String CATEGORY = "Category";
static final String CATEGORY_ID = "Id";
static final String CATEGORY_NAME = "Name";
final InputStream response;
protected MasterdataBaseParser(InputStream response){
this.response = response;
}
protected InputStream getInputStream() {
return response;
}
}
But it displays only "mil" and it is not taking "&" as "&". But i want to display "mil & carbon". How to do this one? Advance thanks for any help
Here is an example of how i do things with one class parser and several xml stream :
public class RSSHandler extends DefaultHandler {
int RSS_ID;
ContentValues parsedValues = new ContentValues();
private String parsedString = null;
protected DataController _dataController;
private StringBuffer parsedBuffer = new StringBuffer();
public void setRssId(int rssId) {
RSS_ID = rssId;
}
public void setDataController(DataController dataController) {
_dataController = (DataController) dataController;
}
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
}
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
parsedString = parsedString.trim();
switch (RSS_ID) {
case (0):
if (localName.equals("Application")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (1):
if (localName.equals("tab")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (2):
if (localName.equals("category")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (3):
if (localName.equals("item")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (4):
if (localName.equals("event")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (5):
if (localName.equals("album")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (6):
if (localName.equals("picture")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
case (7):
if (localName.equals("location")) {
_dataController.insertRowInTable(RSS_ID, parsedValues);
}
else {
parsedValues.put(localName, parsedString);
}
break;
default:
break;
}
parsedString = "";
parsedBuffer = new StringBuffer();
}
#Override
public void characters(char ch[], int start, int length) {
parsedBuffer.append(ch, start, start + length);
parsedString = parsedBuffer.toString();
}
}
DataController is just a global class to acces methods and attributes.
public void insertRowInTable(int tableId, ContentValues myRow) {
String myTable = _tableNameList.get(tableId);
_dataBaseHelper.createRowInTable(myTable, myRow);
}
public void createRowInTable(String tableName, ContentValues values) {
try {
myDataBase.insert(tableName, null, values);
}
catch (Exception e) {
//catch
}
}
While parsing xml, by default "&" is behaving as "Escape sequence"(In android lower version like 2.2) that's why i can't able to parse that "mil & carbon". So before parsing, i replaced "&" with "ampersand"(In words) under the file and after fetching that node as "mil ampersand carbon" then replacing the "ampersand" with "&"(symbol). And lots of thanks to "Yume" sir

Parsing CDATA in android RSS

I'm trying to make an ANDROID app that reads RSS feeds so I used this tutorial ( http://android-er.blogspot.com/2010/05/simple-rss-reader-ii-implement-with.html ) and implemented it to my own url rss feeder. But the description tag isn't being shown..mostly cz in the xml of the feeder the description tags are CDATA. how can i parse the description cdata in my rss??Thanks!
here is my RSSHandler code :
import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;
public class RSSHandler extends DefaultHandler {
final int state_unknown = 0;
final int state_title = 1;
final int state_description = 2;
final int state_link = 3;
final int state_pubdate = 4;
int currentState = state_unknown;
RSSFeed feed;
RSSItem item;
boolean itemFound = false;
RSSHandler(){
}
RSSFeed getFeed(){
return feed;
}
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
feed = new RSSFeed();
item = new RSSItem();
}
#Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
itemFound = true;
item = new RSSItem();
currentState = state_unknown;
}
else if (localName.equalsIgnoreCase("title")){
currentState = state_title;
}
else if (localName.equalsIgnoreCase("description")){
currentState = state_description;
}
else if (localName.equalsIgnoreCase("link")){
currentState = state_link;
}
else if (localName.equalsIgnoreCase("pubdate")){
currentState = state_pubdate;
}
else{
currentState = state_unknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
feed.addItem(item);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch,start,length);
if (itemFound==true){
// "item" tag found, it's item's parameter
switch(currentState){
case state_title:
item.setTitle(strCharacters);
break;
case state_description:
item.setDescription(strCharacters);
break;
case state_link:
item.setLink(strCharacters);
break;
case state_pubdate:
item.setPubdate(strCharacters);
break;
default:
break;
}
}
else{
// not "item" tag found, it's feed's parameter
switch(currentState){
case state_title:
feed.setTitle(strCharacters);
break;
case state_description:
feed.setDescription(strCharacters);
break;
case state_link:
feed.setLink(strCharacters);
break;
case state_pubdate:
feed.setPubdate(strCharacters);
break;
default:
break;
}
}
currentState = state_unknown;
}
and here is my RSSReader code :
public class AndroidRssReader extends ListActivity {
private RSSFeed myRssFeed = null;
//private ArrayList<RSSItem> myRssFeed = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
//URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml");
URL rssUrl = new URL("http://www.merehbi.com/online/index.php?option=com_content&view=category&layout=blog&id=58&Itemid=155&lang=ar&format=feed&type=rss");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (myRssFeed!=null)
{
TextView feedTitle = (TextView)findViewById(R.id.feedtitle);
TextView feedDescribtion = (TextView)findViewById(R.id.feeddescribtion);
TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate);
TextView feedLink = (TextView)findViewById(R.id.feedlink);
feedTitle.setText(myRssFeed.getTitle());
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
ArrayAdapter<RSSItem> adapter =
new ArrayAdapter<RSSItem>(this,
android.R.layout.simple_list_item_1,myRssFeed.getList());
setListAdapter(adapter);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this,ShowDetails.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate", myRssFeed.getItem(position).getPubdate());
intent.putExtras(bundle);
startActivity(intent);
}
}
i use this tutorial and its codes
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
and change some code by this answer
https://stackoverflow.com/a/8489223/3636653
public static void main(String[] args) throws Exception {
File file = new File("data.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("topic");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}

How do parse xml in android using SAX Parser?

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

how to set data in textbox after sax parsing

i parse the xml file and all data will parsed but i dont understand how to set this data in textview ? give me some idea about that
public class GtuItemXMLHandler extends DefaultHandler {
Gtudownload gtudownload;
Questionpaper questionpaper;
// Show me the XML.
private String currentString = "";
private String charactersString = "";
private Branch branch;
private Year year;
private Semester semester;
private int branchCount = 0;
private int yearCount = 0;
private int semesterCount = 0;
// private ArrayList<Gtudownload> itemsList = new ArrayList<Gtudownload>();
//
// public ArrayList<Gtudownload> getItemsList() {
// return itemsList;
// }
public Gtudownload getGtudownload(){
return this.gtudownload;
}
public Questionpaper getQuestionpaper()
{
return this.questionpaper;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i("GTU ", localName);
if (localName.equalsIgnoreCase("Gtudownload")) {
gtudownload = new Gtudownload();
currentString = "Gtudownload";
} else if (localName.equalsIgnoreCase("Questionpaper")) {
gtudownload.setQuestionpaper(new Questionpaper());
gtudownload.getQuestionpaper().setBranchList(new ArrayList<Branch>());
currentString = "Questionpaper";
} else if (localName.equalsIgnoreCase("Branch")) {
branch = new Branch();
gtudownload.getQuestionpaper().getBranchList().add(branch);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).setYearList(new ArrayList<Year>());
currentString = "Branch";
Log.i("Branch", attributes.getValue("value"));
branch.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("Year")) {
year = new Year();
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().add(year);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).setSemesterList(new ArrayList<Semester>());
currentString = "Year";
Log.i("Year ", attributes.getValue("value"));
year.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("semester")) {
semester = new Semester();
currentString = "semester";
Log.i("Semester ", attributes.getValue("value"));
semester.setValue(attributes.getValue("value"));
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().add(semester);
} else if (localName.equalsIgnoreCase("url")){
currentString = "url";
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("Questionpaper")){
branchCount=0;
}else if(localName.equalsIgnoreCase("Branch")){
yearCount = 0;
branchCount++;
}else if(localName.equalsIgnoreCase("Year")){
semesterCount = 0;
yearCount++;
}else if(localName.equalsIgnoreCase("semester")){
semesterCount++;
}else if(localName.equalsIgnoreCase("url")){
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().get(semesterCount).setUrl(charactersString);
Log.i("URL", charactersString);
}
currentString = "";
charactersString= "";
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
charactersString = new String(ch, start, length);
charactersString = charactersString.trim();
}
}
this is my activity and how can i set this parsing data in into textview
public class GtudldActivity extends Activity {
/** Called when the activity is first created. */
private TextView xmlOutput;
TextView example[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
xmlOutput = (TextView) findViewById(R.id.xmlOutput);
Gtudownload gtudownload = parseXML();
}
private Gtudownload parseXML() {
Gtudownload gtudownload = null;
try {
Log.w("AndroidParseXMLActivity", "Start");
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
GtuItemXMLHandler myXMLHandler = new GtuItemXMLHandler();
xr.setContentHandler(myXMLHandler);
InputSource is = new InputSource(getResources().openRawResource(R.raw.mgtu));
gtudownload = myXMLHandler.getGtudownload();
Log.i("Data",gtudownload+"");
xr.parse(is);
} catch (Exception e) {
Log.w("AndroidParseXMLActivity", e);
}
//xmlOutput.setText(gtudownload.toString());
return gtudownload;
}
}
You'll get so many examples for this on google. I am showing you one of the. Just try this
I hope it may help you. If you've any doubt, just post it here

Categories

Resources