I was trying to parse XML from a url and show it on a listview. But, listview is showing
like this
http://postimg.org/image/ucbdjpwj5/
[I can't post any image directly here, because my reputation is under 10 ]
Here are my code
MainActivity
getRssDataTask ts = new getRssDataTask();
ts.execute("http://www.xyzapp.com/feed");
}
private class getRssDataTask extends AsyncTask<String, Void, List<NewsItem>>{
#Override
protected List<NewsItem> doInBackground(String... params) {
// TODO Auto-generated method stub
try {
// Create RSS reader
RSSReader rssReader = new RSSReader(params[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("App", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<NewsItem> result) {
ListView Items = (ListView) findViewById(R.id.listView);
// Create a list adapter
ArrayAdapter<NewsItem> rs = new ArrayAdapter<NewsItem>(local,android.R.layout.simple_list_item_1, result);
// Set list adapter for the ListView
Items.setAdapter(rs);
RssHandler
public class RssHandler extends DefaultHandler {
private List<NewsItem> rssItem;
private NewsItem currentItem;
private boolean parsingTitle;
private boolean parsingDes;
public RssHandler() {
// TODO Auto-generated constructor stub
rssItem = new ArrayList<NewsItem>();
}
public List<NewsItem> getItems() {
return rssItem;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if ("item".equals(qName)) {
currentItem = new NewsItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("content:encoded".equals(qName)) {
parsingDes = true;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if ("item".equals(qName)) {
rssItem.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
} else if ("content:encoded".equals(qName)) {
parsingDes = false;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
} else if (parsingDes) {
if (currentItem != null) {
currentItem.setDes(new String(ch, start, length));
parsingDes = false;
}
}
}
}
RssReader
public class RSSReader {
private String RssUrl;
public RSSReader(String RssUrl) {
// TODO Auto-generated constructor stub
this.RssUrl = RssUrl;
}
public List<NewsItem> getItems() throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssHandler handler = new RssHandler();
saxParser.parse(RssUrl, handler);
return handler.getItems();
}
}
I was unable to figure out the problem. My question is what wrong I am doing ?
Implement the following method in NewsItem:
#Override
public String toString() {
// return a String value representing this object
// Assuming two class String properties called title and description
return title + ": " + description;
}
Related
I'm developing an Xml parsing application. The URL is not trusted when it is opened from the browser. There is no way to correct it from server side. So I used "trsut anybody" code.
But still I'm getting a null pointer exception.
Please help me with this.
Thanx in advance
this is my code.
public class SitesList {
/** Variables */
private ArrayList<String> From_Currency = new ArrayList<String>();
private ArrayList<String> To_Currency = new ArrayList<String>();
private ArrayList<String> exrt_buy = new ArrayList<String>();
private ArrayList<String> exrt_sell = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getFrom_Currency() {
return From_Currency;
}
public void setFrom_Currency(String From_Currency) {
this.From_Currency.add(From_Currency);
}
public ArrayList<String> getTo_Currency() {
return To_Currency;
}
public void setTo_Currency(String To_Currency) {
this.To_Currency.add(To_Currency);
}
public ArrayList<String> getexrt_buy() {
return exrt_buy;
}
public void setexrt_buy(String exrt_buy) {
this.exrt_buy.add(exrt_buy);
}
public ArrayList<String> getexrt_sell() {
return exrt_sell;
}
public void setexrt_sell(String exrt_sell) {
this.exrt_sell.add(exrt_sell);
}
}
MyXMLHandler class
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("DOC"))
{
sitesList = new SitesList();
}
/*} 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;
if (localName.equalsIgnoreCase("From_Currency"))
sitesList.setFrom_Currency(currentValue);
else if (localName.equalsIgnoreCase("To_Currency"))
sitesList.setTo_Currency(currentValue);
else if (localName.equalsIgnoreCase("exrt_buy"))
sitesList.setexrt_buy(currentValue);
else if (localName.equalsIgnoreCase("exrt_sell"))
sitesList.setexrt_sell(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
XMLParsingExample class
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
URL url;
HttpsURLConnection https;
HttpURLConnection conn = null;
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
url = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
try {
https = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
} else {
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
/** 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 From_Currency[];
TextView To_Currency[];
TextView exrt_buy[];
TextView exrt_sell[];
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("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
From_Currency = new TextView[sitesList.getFrom_Currency().size()];
To_Currency = new TextView[sitesList.getTo_Currency().size()];
exrt_buy = new TextView[sitesList.getexrt_buy().size()];
exrt_sell = new TextView[sitesList.getexrt_sell().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getFrom_Currency().size(); i++) {
From_Currency[i] = new TextView(this);
From_Currency[i].setText("Name = "+sitesList.getFrom_Currency().get(i));
To_Currency[i] = new TextView(this);
To_Currency[i].setText("Website = "+sitesList.getTo_Currency().get(i));
exrt_buy[i] = new TextView(this);
exrt_buy[i].setText("Website Category = "+sitesList.getexrt_buy().get(i));
exrt_sell[i] = new TextView(this);
exrt_sell[i].setText("Website Category = "+sitesList.getexrt_sell().get(i));
layout.addView(From_Currency[i]);
layout.addView(To_Currency[i]);
layout.addView(exrt_buy[i]);
layout.addView(exrt_sell[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
private void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
The RSS Reader doesent fetch HTML Characters like "#8220;" so when the feed is "Hey#8220;" the App shows only "Hey" but i doesent know why. I tried things like Html.fromHtml, but it doesent work. Does anyone see the mistake?
Thanks for answers
`public class AndroidRssReader extends ListActivity {
private RSSFeed myRssFeed = null;
TextView feedTitle;
TextView feedDescribtion;
TextView feedPubdate;
TextView feedLink;
public class MyCustomAdapter extends ArrayAdapter<RSSItem> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem> list) {
super(context, textViewResourceId, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView listTitle=(TextView)row.findViewById(R.id.listtitle);
listTitle.setText(myRssFeed.getList().get(position).getTitle());
TextView listPubdate=(TextView)row.findViewById(R.id.listpubdate);
listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
if (position%2 == 0){
listTitle.setBackgroundColor(0xff101010);
listPubdate.setBackgroundColor(0xff101010);
}
else{
listTitle.setBackgroundColor(0xff080808);
listPubdate.setBackgroundColor(0xff080808);
}
return row;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
feedTitle = (TextView)findViewById(R.id.feedtitle);
feedDescribtion = (TextView)findViewById(R.id.feeddescribtion);
feedPubdate = (TextView)findViewById(R.id.feedpubdate);
feedLink = (TextView)findViewById(R.id.feedlink);
readRss();
}
private void readRss(){
feedTitle.setText("--- wait ---");
feedDescribtion.setText("");
feedPubdate.setText("");
feedLink.setText("");
setListAdapter(null);
Toast.makeText(this, "News werden geladen...", Toast.LENGTH_LONG).show();
try {
URL rssUrl = new URL("MYURL");
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed!=null)
{
Calendar c = Calendar.getInstance();
String strCurrentTiime = "\n(Time of Reading - "
+ c.get(Calendar.HOUR_OF_DAY)
+ " : "
+ c.get(Calendar.MINUTE) + ")\n";
feedTitle.setText(myRssFeed.getTitle() + strCurrentTiime);
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
MyCustomAdapter adapter =
new MyCustomAdapter(this, R.layout.row, myRssFeed.getList());
setListAdapter(adapter);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
/*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);*/
Uri feedUri = Uri.parse(myRssFeed.getItem(position).getLink());
Intent myIntent = new Intent(Intent.ACTION_VIEW, feedUri);
startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 0, 0, "Refresh");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case (0): readRss();
break;
default:
break;
}
return true;
}
}`
public class RSSFeed {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
private List<RSSItem> itemList;
RSSFeed(){
itemList = new Vector<RSSItem>(0);
}
void addItem(RSSItem item){
itemList.add(item);
}
RSSItem getItem(int location){
return itemList.get(location);
}
List<RSSItem> getList(){
return itemList;
}
void setTitle(String value)
{
title = value;
}
void setDescription(String value)
{
description = value;
}
void setLink(String value)
{
link = value;
}
void setPubdate(String value)
{
pubdate = value;
}
String getTitle()
{
return title;
}
String getDescription()
{
return description;
}
String getLink()
{
return link;
}
String getPubdate()
{
return pubdate;
}
}
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;
}
}
public class RSSItem {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
RSSItem(){
}
void setTitle(String value)
{
value.replace("#8220;", "hi");
title =value;
}
void setDescription(String value)
{
description = value;
}
void setLink(String value)
{
link = value;
}
void setPubdate(String value)
{
pubdate = value;
}
String getTitle()
{
return title;
}
String getDescription()
{
return description;
}
String getLink()
{
return link;
}
String getPubdate()
{
return pubdate;
}
/*#Override
public String toString() {
// TODO Auto-generated method stub
return title;
}*/
}
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
Set an encoding to your input source or stream. This sample code can help you.
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 have a xml like this :
<channel>
<item>
<link>http://uopnews.unipune.ac.in/Lists/Calendar/DispForm.aspx?ID=14</link>
<description><![CDATA[<div><b>Location:</b> PUMBA Auditorium - University of Pune</div> <div><b>Start Time:</b> 5/15/2012 11:00 AM</div>
<div><b>End Time:</b> 5/15/2012 2:00 PM</div>
<div><b>Description:</b> <div>General B. C. Joshi Memorial Lecture 2012- Perspective on War in the 21st Century - By Lt. Gen. A. K. Singh</div></div>
<div><b>Attachments:</b> http://uopnews.unipune.ac.in/Lists/Calendar/Attachments/14/bcjoshi2012[1].pdf<br></div>
]]></description>
</item>
</channel>
I can parse upto description tag using SAX Parser here is my SAXhandler class.
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.R.string;
import android.util.Log;
public class XMLParsingHandler extends DefaultHandler {
private static final String NEW_DATA_SET = "image";
private String currentValue = "";
private String currentTag = "";
private HashMap<String, Object> root;
private HashMap<String, String> child;
private String[] tagArray = null;
private ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
private String describe;
public XMLParsingHandler(String[] tagArray) {
this.tagArray = tagArray;
}
public void parseContent(String urlStr) {
try {
URL url = new URL(urlStr);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
xmlReader.parse(new InputSource(url.openStream()));
Log.d("PRASER", "Afer parsering done" + arraylist);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
root = new HashMap<String, Object>();
System.out.println("root=" + root);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
Log.d("tag", "StartElement started here");
currentTag = localName;
Log.d("start", "in start doc current atg---------: " + currentTag);
if (localName.equals(NEW_DATA_SET)) {
child = new HashMap<String, String>();
currentValue = new String();
}
describe=new String();
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
currentValue = new String(ch, start, length);
Log.d("other", "in CHARACTER : CurrentValue=---------" + currentValue
+ " currentTag-------" + currentTag);
if(currentTag.equals("description") ) {
String str= new String(ch, start, length);
//describe=new String();
describe=describe+""+currentValue;
Log.d("describe", "in CHARACTER : describe=---------" + describe);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
Log.d("end", "currentTag:"+currentTag+"------currentValue"+currentValue);
if(child!=null)
{
for (int i = 0; i < tagArray.length; i++) {
if (currentTag.equals("description")){
child.put(currentTag, currentValue);
}
if (currentTag.equals(tagArray[i]))
{
child.put(currentTag, currentValue);
Log.d("tagarray","currentTag="+ currentTag+"currentValue:"+currentValue);
currentValue=null;
currentValue=new String();
currentTag=null;
currentTag=new String();
}
}
if (localName.equals(tagArray[tagArray.length - 1])) {
arraylist.add(child);
child=null;
child=new HashMap<String, String>();
}
}
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
Log.d("tag", "in end doc");
}
public ArrayList<HashMap<String, String>> getArraylist() {
return arraylist;
}
public void setArraylist(ArrayList<HashMap<String, String>> arraylist) {
this.arraylist = arraylist;
}
#Override
public String toString() {
return arraylist.toString();
}
}
and I am Calling it like this :
userMap = new HashMap<String, String>();
XMLParsingHandler x = new XMLParsingHandler(tagArray);
x.parseContent(url);
System.out.println("Element FOund");
userMap = x.getArraylist().get(0);
System.out.println("Map " + userMap);
here my userMap only print valu upto description tag after it only shows null value. i need all data from description. Is there any way?
Find the below sax parser code
public class IndianNewsHandler implements ContentHandler {
private String value = "";
private Item item = null;
private TextView tvRef = null;
private Activity myActivity = null;
private static IndianNewsHandler mIndianNewsHandler;
public static IndianNewsHandler getInstance() {
if (mIndianNewsHandler == null) {
mIndianNewsHandler = new IndianNewsHandler();
}
return mIndianNewsHandler;
}
private IndianNewsHandler() {
}
private ArrayList<Item> content = new ArrayList<Item>();
// private ArrayList<String> myList = new ArrayList<String>();
private boolean STATUS_PARSE = true;
private boolean ITEM_STATUS = false;
public ArrayList<Item> getData() {
return content;
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (STATUS_PARSE) {
this.value = localName;
if (localName.equals("item")) {
item = new Item();
ITEM_STATUS = true;
}
}
}
public void characters(char[] text, int start, int length)
throws SAXException {
if (STATUS_PARSE && ITEM_STATUS) {
StringBuffer buffer = new StringBuffer();
buffer.append(text, 0, length);
if (buffer != null) {
if (this.value.equals("title")) {
System.out.println("I am in title"
+ buffer.toString().trim());
if (buffer.toString().trim().length() > 1)
item.setTitle(buffer.toString().trim());
} else if (value.equals("description"))
{
String url = buffer.toString().trim();
try {
if (url.contains("img src=")) {
final String url_string = url.split("img src=")[1]
.split(">")[0].replace("'", "");
System.out.println("FInal URL :" + url_string);
if (url_string != null) {
//here i am creating async task for convert image
new CovertingImageToByte(url_string).execute();
if (buffer.toString().trim().length() > 1) {
String des = buffer.toString().split(">")[1];
item.setDes(des);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class CovertingImageToByte extends AsyncTask<String,Integer, String>{
String imageUrl;
public CovertingImageToByte(String urlString) {
this.imageUrl=urlString;
}
#Override
protected String doInBackground(String... params) {
try {
InputStream is = new URL(imageUrl)
.openStream();
Bitmap bitmap = BitmapFactory
.decodeStream(is);
byte[] mybyt = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG,
0, stream);
mybyt = stream.toByteArray();
System.out.println("test"
+ mybyt.length);
item.setImg(mybyt);
// System.out.println("Finallly List123 size ::::::::::"+content.get(0).getImg().length);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (STATUS_PARSE) {
if (localName.equals("item")) {
content.add(item);
}
if (content.size() >= 15) {
STATUS_PARSE = false;
}
}
}
#Override
// do nothing methods
public void setDocumentLocator(Locator locator) {
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
System.out.println("Finallly List size ::::::::::" + content.get(1));
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {
}
public void skippedEntity(String name) throws SAXException {
}
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException {
}
public void processingInstruction(String target, String data)
throws SAXException {
}
}
I am trying to use the API for our billing system in an Android Application, but I am having trouble figuring out how to parse the XML that it returns. Here is what my function looks like thus far...
public void ParseData(String xmlData)
{
try
{
// Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
// Input Stream
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlData));
// Parse Document into a NodeList
Document doc = db.parse(inStream);
NodeList nodes = doc.getElementsByTagName("ticket");
// Loop NodeList and Retrieve Element Data
for(int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
if (node instanceof Element)
{
Element child = (Element)node;
String id = child.getAttribute("id");
}
}
}
catch(SAXException e)
{
}
}
and here is what the XML data looks like that is returned. I need to loop through each and pull each element out, but I cant figure out how to do that with the DOM parser.
<whmcsapi>
<action>gettickets</action>
<result>success</result>
<totalresults>1</totalresults>
<startnumber>0</startnumber>
<numreturned>1</numreturned>
<tickets>
<ticket>
<id>1</id>
<tid>557168</tid>
<deptid>1</deptid>
<userid>1</userid>
<name><![CDATA[Array]]></name>
<email></email>
<cc></cc>
<c>TmDEga5v</c>
<date>2009-08-03 23:14:32</date>
<subject><![CDATA[Test Ticket]]></subject>
<message><![CDATA[This is a test ticket>
----------------------------
IP Address: xxx.xxx.xxx.xxx]]></message>
<status>Open</status>
<priority>Medium</priority>
<admin></admin>
<attachment></attachment>
<lastreply>2009-08-04 12:14:18</lastreply>
<flag>0</flag>
<service></service>
</ticket>
</tickets>
</whmcsapi>
Yes SAX parser is the solution and here is the basic code to get you started:
void parseExampleFunction(){
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
File myFile = new File( //the XML file which you need to parse );
myFile.createNewFile();
FileInputStream fOut = new FileInputStream(myFile);
BufferedInputStream bos = new BufferedInputStream( fOut );
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MessagesXMLHandler myXMLHandler = new MessagesXMLHandler(context);
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(bos));
}
// the class where the parsing logic needs to defined.This preferably can be in a different .java file
public class MessagesXMLHandler extends DefaultHandler{
//this function is called automatically when a start tag is encountered
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
//variable localName is the name of the tag
//this function is called autiomatically when an end tag is encountered
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
}
//this function gets called to return the value stored betweeen the closing and opening tags
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
//now variable value has the value stored between the closing and opening tags
String value=new String(ch,start,length);
}
}
for parse xml on android best way is to use SAXParser. i explained it bellow with demo....
first of all create your activity class like as bellw.
public class ActivityForSax extends ListActivity {
private ProgressDialog pDialog;
private ItemXMLHandler myXMLHandler;
private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
private TextView textview;
private ListView mListView;
private ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_dom);
textview = (TextView)findViewById(R.id.textView1);
doParsing();
mListView = getListView();
}
public void doParsing(){
if (isNetworkAvailable()) {
textview.setText("Loading...Please wait...");
new AsyncData().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
class AsyncData extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
menuItems = new ArrayList<HashMap<String, String>>();
pDialog = new ProgressDialog(ActivityForSax.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new ItemXMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
} catch (ParserConfigurationException pce) {
Log.e("SAX XML", "sax parse error", pce);
} catch (SAXException se) {
Log.e("SAX XML", "sax error", se);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
textview.setText("Done!!!");
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
for (int i = 0; i < itemsList.size(); i++) {
Bean objBean = itemsList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("TITLE :: ", objBean.getTitle());
map.put("DESC :: ", objBean.getDesc());
map.put("PUBDATE :: ", objBean.getPubDate());
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(ActivityForSax.this, menuItems,
R.layout.list_item,
new String[] { "TITLE :: ", "DESC :: ", "PUBDATE :: " }, new int[] {
R.id.name, R.id.email, R.id.mobile });
mListView.setAdapter(adapter);
}
}
public void showToast(String msg) {
Toast.makeText(ActivityForSax.this, msg, Toast.LENGTH_LONG).show();
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
now you need to create default handler class for parsing xml data.
public class ItemXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = "";
Bean item = null;
private ArrayList<Bean> itemsList = new ArrayList<Bean>();
public ArrayList<Bean> getItemsList() {
return itemsList;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if (localName.equals("item")) {
item = new Bean();
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equals("id")) {
item.setId(currentValue);
} else if (localName.equals("title")) {
item.setTitle(currentValue);
} else if (localName.equals("desc")) {
item.setDesc(currentValue);
} else if (localName.equals("pubDate")) {
item.setPubDate(currentValue);
} else if (localName.equals("link")) {
item.setLink(currentValue);
} else if (localName.equals("item")) {
itemsList.add(item);
}
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}
and finally your Bean class like as...
public class Bean {
private String id;
private String title;
private String desc;
private String pubDate;
private String link;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
Add java-json.jar in library folder
Compile files ('libs/java-json.jar') //add this line into your build
Here is the code to convert xml response to json response:
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}