read rss feed - android - android

I'm trying to develop a simple application that reads rss feeds from a certain URL and then displays the results in a list view.
Here is my rss reader, which is the main thing in the app:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssReader {
private String title = null;
private String link = null;
private String description = null;
private ArrayList<RssItem> posts = new ArrayList<RssItem>();
private Thread thread;
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public RssReader(String url) {
this.urlString = url;
}
public boolean getParsingComplete() {
return this.parsingComplete;
}
public ArrayList<RssItem> getPosts() {
return posts;
}
public void parseXML(XmlPullParser parser) {
int event;
try {
event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = parser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.END_TAG:
if (name.equals("title")) {
title = parser.getText();
} else if (name.equals("link")) {
link = parser.getText();
} else if (name.equals("description")) {
description = parser.getText();
}
break;
}
if(title != null && link != null && description != null) {
RssItem item = new RssItem(this.title,this.description,this.link);
posts.add(item);
this.title = this.description = this.link = null;
}
event = parser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML() {
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(
XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXML(myparser);
stream.close();
} catch (Exception e) {
} finally {
parsingComplete = true;
}
}
});
thread.start();
}
And here is my MainActivity:
package com.example.ynetrssproject;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.ListView;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity {
private ListView news;
private String rssUrl = "http://www.themarker.com/cmlink/1.144";
private ArrayList<RssItem> list;
private RssItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
news = (ListView) findViewById(R.id.news);
RssReader reader = new RssReader(rssUrl);
reader.fetchXML();
while(true) {
Log.d("Runnning", "Run");
if(reader.getParsingComplete()) {
list = reader.getPosts();
break;
}
}
adapter = new RssItemAdapter(this, R.layout.post_item_list, list);
news.setAdapter(adapter);
}
}
The problem is that everytime I call fetchXML, eventually it returns me an empty ArrayList. Therefore, my listview keeps being empty.
My adapter isn't such a big deal. It works fine. The problem is that I keep getting an empty array list from the object RssReader. I know this because I performed a little if statement at the end of the code just to check if the ArrayList is empty.
P.S I have tried with multiple RSS urls but none of them works.
Also, I added the permission of Internet in my manifest.

use SAXParser
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("link".equals(qName)) {
parsingLink = true;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
}else if ("title".equals(qName)) {
parsingTitle = false;
}else if ("link".equals(qName)) {
parsingLink = false;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
}else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
public class RssItem {
// item title
private String title;
// item link
private String link;
private String id;
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 getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#Override
public String toString() {
return title;
}
}

Related

Send ArrayAdapter<rss> into another activity intent

i want to make rss reader app.
i want to get rss first then pass it into another activity use intent.
here is my codes:
mainActivity.java
public class mainActivity extends Activity {
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
RssParser parser = new RssParser("https://test/feed/");
Bundle extra = new Bundle();
extra.putSerializable("objects", parser);
Intent intent = new Intent(this, b.class);
intent.putExtra("extra", extra);
startActivity(intent);
}
}
RssParser.java
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
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 org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssParser extends DefaultHandler implements Serializable {
private StringBuilder content;
private boolean inChannel;
private boolean inImage;
private boolean inItem;
private ArrayList<Item> items = new ArrayList<Item>();
private Channel channel = new Channel();
private Item lastItem;
public RssParser(String url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
xr.setContentHandler(this);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Item {
public String title;
public String description;
public String link;
public String category;
public String pubDate;
public String guid;
public String imageUrl;
public String creator;
}
public class Channel {
public String title;
public String description;
public String link;
public String lastBuildDate;
public String generator;
public String imageUrl;
public String imageTitle;
public String imageLink;
public String imageWidth;
public String imageHeight;
public String imageDescription;
public String language;
public String copyright;
public String pubDate;
public String category;
public String ttl;
}
#Override
public void startDocument() throws SAXException {
// Log.i("LOG", "StartDocument");
}
#Override
public void endDocument() throws SAXException {
// Log.i("LOG", "EndDocument");
}
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = true;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = true;
}
if (localName.equalsIgnoreCase("item")) {
lastItem = new Item();
items.add(lastItem);
inItem = true;
}
content = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = false;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = false;
}
if (localName.equalsIgnoreCase("item")) {
inItem = false;
}
if (localName.equalsIgnoreCase("title")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.title = content.toString();
} else if (inImage) {
channel.imageTitle = content.toString();
} else if (inChannel) {
channel.title = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("dc:creator") || localName.equalsIgnoreCase("creator")) {
if (content == null) {
return;
}
lastItem.creator = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("description")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.description = android.text.Html.fromHtml(content.toString()).toString().substring(1);
lastItem.imageUrl = this.extractImageUrl(content.toString());
} else if (inImage) {
channel.imageDescription = content.toString();
} else if (inChannel) {
channel.description = android.text.Html.fromHtml(content.toString()).toString().substring(1);
}
content = null;
}
if (localName.equalsIgnoreCase("link")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.link = content.toString();
} else if (inImage) {
channel.imageLink = content.toString();
} else if (inChannel) {
channel.link = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("category")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.category = content.toString();
} else if (inChannel) {
channel.category = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("pubDate")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.pubDate = content.toString();
} else if (inChannel) {
channel.pubDate = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("guid")) {
if (content == null) {
return;
}
lastItem.guid = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("url")) {
if (content == null) {
return;
}
channel.imageUrl = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("width")) {
if (content == null) {
return;
}
channel.imageWidth = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("height")) {
if (content == null) {
return;
}
channel.imageHeight = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("language")) {
if (content == null) {
return;
}
channel.language = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("copyright")) {
if (content == null) {
return;
}
channel.copyright = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("ttl")) {
if (content == null) {
return;
}
channel.ttl = content.toString();
content = null;
}
}
private String extractImageUrl(String description) {
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
}
catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
XmlPullParser xpp = null;
try {
xpp = factory.newPullParser();
}
catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
xpp.setInput(new StringReader(description));
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int eventType = 0;
try {
eventType = xpp.getEventType();
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && "img".equals(xpp.getName())) {
//found an image start tag, extract the attribute 'src' from here...
return xpp.getAttributeValue(null, "src").toString();
}
try {
eventType = xpp.next();
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return xpp.getAttributeValue(null, "src").toString();
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (content == null) {
return;
}
content.append(ch, start, length);
}
public Item getItem(int index) {
return items.get(index);
}
public ArrayList<Item> getItems() {
return items;
}
}
second activity that i want to get RssParser Items:
b.java
Bundle extra = getIntent().getBundleExtra("extra");
RssParser p = (RssParser) extra.getSerializable("objects");
ListView listView = (ListView) findViewById(R.id.content_frame);
listView.setAdapter((ListAdapter) p.getItems());
and i always get errors like:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
java.lang.RuntimeException: Parcel: unable to marshal value
Caused by: java.lang.RuntimeException: Parcelable encountered IOException reading a Serializable object
if any suggestion i really Thankful.
Best Regards
In this case, instead of extending from Serializable, extend from Parcelable.
And, when sending, use:
RssParser parser = new RssParser("https://test/feed/");
Bundle extra = new Bundle();
extra.putParcelable("objects", parser);
Reception of it:
RssParser rssParser = getIntent().getExtras().getParcelable("objects");
Works like that, not precisely the best option, but works.
The error mainly said that was found a Serializable when a Parcelable was received. So, I changed it to Parcelable.
EDIT
gradle:
dependencies {
//...
compile 'com.google.code.gson:gson:2.2.4'
}
Send:
Intent intent = new Intent(MainActivity.this, b.class);
intent.putExtra("extra", new Gson().toJson(parser));
startActivity(intent);
Receive:
String toParse = getIntent().getExtras().getString("extra");
RssParser rssParser = new Gson().fromJson(toParse, RssParser.class);
From the edit, i was tested. It works.
EDIT2
If, you need to pass a Array or List:
Type rssListType = new TypeToken<ArrayList<RssParser>>(){}.getType();
List<RssParser> founderList = new Gson().fromJson(myStringToParse, rssListType);
Regards.

Android:parsing XML returns no value

I created an app that is going to download an xml file,then parse it, and adapt it to a list view, but I faced a problem in parsing xml, first thing first:
MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadData downloadData = new downloadData();
downloadData.execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml");
}
private class downloadData extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ParseApplications parseApplications = new ParseApplications();
parseApplications.parse(s);
}
#Override
protected String doInBackground(String... params) {
String rssFeed = downloadXML(params[0]);
if (rssFeed == null) {
}
return rssFeed;
}
private String downloadXML(String urlPath) {
StringBuilder xmlResult = new StringBuilder();
try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charsRead;
char[] inputBuffer = new char[500];
while (true) {
charsRead = reader.read(inputBuffer);
if (charsRead < 0) {
break;
}
if (charsRead > 0) {
xmlResult.append(String.copyValueOf(inputBuffer), 0, charsRead);
}
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return xmlResult.toString();
}
}
}
MainActivity.class work well in term of downloading XML, but when it comes to parsing xml, although it parses it,but return no value:
ParseApplications.java
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.ArrayList;
public class ParseApplications {
private ArrayList<FeedEntry> applications;
public ParseApplications() {
this.applications = new ArrayList<>();
}
public ArrayList<FeedEntry> getApplications() {
return applications;
}
public boolean parse(String xmlData) {
boolean status = true;
FeedEntry currentRecord = null;
boolean inEntry = false;
String textValue = "";
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xmlData));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if ("entry".equalsIgnoreCase(tagName)) {
inEntry = true;
currentRecord = new FeedEntry();
}
break;
case XmlPullParser.TEXT:
textValue = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (inEntry) {
if ("entry".equalsIgnoreCase(tagName)) {
applications.add(currentRecord);
inEntry = false;
} else if ("name".equalsIgnoreCase(tagName)) {
currentRecord.setName(textValue);
} else if ("artist".equalsIgnoreCase(tagName)) {
currentRecord.setArtist(textValue);
} else if ("releaseDate".equalsIgnoreCase(tagName)) {
currentRecord.setReleaseDate(textValue);
} else if ("image".equalsIgnoreCase(tagName)) {
currentRecord.setImageURL(textValue);
} else if ("summary".equalsIgnoreCase(tagName)) {
currentRecord.setSummary(textValue);
}
}
break;
default:
//Nothing to do
eventType = xpp.next();
}
}
} catch (Exception e) {
status = false;
e.printStackTrace();
}
return status;
}
}
here is the other class:
FeedEntry.java
public class FeedEntry {
private String name;
private String artist;
private String releaseDate;
private String summary;
private String imageURL;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
#Override
public String toString() {
return "name='" + name + '\n' +
", artist='" + artist + '\n' +
", releaseDate='" + releaseDate + '\n' +
", imageURL='" + imageURL;
}
}
I think I am a quiet bit late but still, it can help other also. So I am posting my answer. Please check the parse method once you are stuck at first tag only.It should be like this
public boolean parse(String xmlData) {
boolean status = true;
FeedEntry currentRecord = null;
boolean inEntry = false;
String textValue = "";
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xmlData));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagName.equalsIgnoreCase("entry")) {
inEntry = true;
currentRecord = new FeedEntry();
}
break;
case XmlPullParser.TEXT:
textValue = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (inEntry) {
if (tagName.equalsIgnoreCase("entry")) {
applications.add(currentRecord);
inEntry = false;
} else if (tagName.equalsIgnoreCase("name")) {
currentRecord.setName(textValue);
} else if (tagName.equalsIgnoreCase("artist")) {
currentRecord.setArtist(textValue);
} else if (tagName.equalsIgnoreCase("releaseDate")) {
currentRecord.setReleaseDate(textValue);
} else if (tagName.equalsIgnoreCase("image")) {
currentRecord.setImageURL(textValue);
} else if (tagName.equalsIgnoreCase("summary")) {
currentRecord.setSummary(textValue);
}
}
break;
default:
//Nothing to do
break;
}
eventType = xpp.next(); // this should come after switch case
}
} catch (
Exception e
)
{
status = false;
e.printStackTrace();
}
return status;
}
In the XmlPullParser.END_TAG: case:
Try to remove "inEntry = false;"

how to do nested parsing using SAX Parser in android

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 {
}
}

Parse XML on Android

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

How to Build a RSS reader for Android?

I am new to android and i am trying to build a RSS reader for Android. I have built all the classes and XML files but its not giving the required output. Its just showing the message
No RSS feed available.
Please can some one suggest what should i do.
Here is the code which i took from the tutorial and tried to manipulate-
public final String RSSFEEDOFCHOICE = "http://blog.01synergy.com/feed/";
public final String tag = "RSSReader";
private RSSFeed feed = null;
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// go get our feed!
feed = getFeed(RSSFEEDOFCHOICE);
// display UI
UpdateDisplay();
}
private RSSFeed getFeed(String urlToRssFeed)
{
try
{
// setup the url
URL url = new URL(urlToRssFeed);
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
RSSHandler theRssHandler = new RSSHandler();
// assign our handler
xmlreader.setContentHandler(theRssHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
return theRssHandler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
return null;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0,0,0, "Choose RSS Feed");
menu.add(0,1,0, "Refresh");
Log.i(tag,"onCreateOptionsMenu");
return true;
}
public boolean onOptionsItemSelected(Menu item){
switch (((View) item).getId()) {
case 0:
Log.i(tag,"Set RSS Feed");
return true;
case 1:
Log.i(tag,"Refreshing RSS Feed");
return true;
}
return false;
}
private void UpdateDisplay()
{
TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate);
ListView itemlist = (ListView) findViewById(R.id.itemlist);
if (feed == null)
{
feedtitle.setText("No RSS Feed Available");
return;
}
feedtitle.setText(feed.getTitle());
feedpubdate.setText(feed.getPubDate());
ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems());
itemlist.setAdapter(adapter);
itemlist.setOnItemClickListener(this);
itemlist.setSelection(0);
}
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
startSubActivity(itemintent,0);
}
private void startSubActivity(Intent itemintent, int i) {
// TODO Auto-generated method stub
}
}
This is my first approach to RSS Reader, It's no so dynamic and has boilerplate code but worked well for myself.
Usage:
RssParser parser = new RssParser(feedUrl);
Log.i("LOG", "Description: " + parser.getItem(3).description); //4th item's description
Class:
package com.uncocoder.course.app.feed_reader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
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.util.Log;
public class RssParser extends DefaultHandler {
private StringBuilder content;
private boolean inChannel;
private boolean inImage;
private boolean inItem;
private ArrayList<Item> items = new ArrayList<Item>();
private Channel channel = new Channel();
private Item lastItem;
public RssParser(String url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
xr.setContentHandler(this);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Item {
public String title;
public String description;
public String link;
public String category;
public String pubDate;
public String guid;
}
public class Channel {
public String title;
public String description;
public String link;
public String lastBuildDate;
public String generator;
public String imageUrl;
public String imageTitle;
public String imageLink;
public String imageWidth;
public String imageHeight;
public String imageDescription;
public String language;
public String copyright;
public String pubDate;
public String category;
public String ttl;
}
#Override
public void startDocument() throws SAXException {
Log.i("LOG", "StartDocument");
}
#Override
public void endDocument() throws SAXException {
Log.i("LOG", "EndDocument");
}
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = true;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = true;
}
if (localName.equalsIgnoreCase("item")) {
lastItem = new Item();
items.add(lastItem);
inItem = true;
}
content = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = false;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = false;
}
if (localName.equalsIgnoreCase("item")) {
inItem = false;
}
if (localName.equalsIgnoreCase("title")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.title = content.toString();
} else if (inImage) {
channel.imageTitle = content.toString();
} else if (inChannel) {
channel.title = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("description")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.description = content.toString();
} else if (inImage) {
channel.imageDescription = content.toString();
} else if (inChannel) {
channel.description = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("link")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.link = content.toString();
} else if (inImage) {
channel.imageLink = content.toString();
} else if (inChannel) {
channel.link = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("category")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.category = content.toString();
} else if (inChannel) {
channel.category = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("pubDate")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.pubDate = content.toString();
} else if (inChannel) {
channel.pubDate = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("guid")) {
if (content == null) {
return;
}
lastItem.guid = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("url")) {
if (content == null) {
return;
}
channel.imageUrl = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("width")) {
if (content == null) {
return;
}
channel.imageWidth = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("height")) {
if (content == null) {
return;
}
channel.imageHeight = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("language")) {
if (content == null) {
return;
}
channel.language = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("copyright")) {
if (content == null) {
return;
}
channel.copyright = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("ttl")) {
if (content == null) {
return;
}
channel.ttl = content.toString();
content = null;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (content == null) {
return;
}
content.append(ch, start, length);
}
public Item getItem(int index) {
return items.get(index);
}
}
Check following link, It's open source RSS reader for Android, You can download code for reference
http://code.google.com/p/android-rss/
There is a tutorial (including complete source code) on how to build an Android RSS reder here:
part 1 (complete application)
part 2 (application updated to parse image tags from desciption)
part 3 (application update with Android 3.0)
The tutorial uses SAX parser and includes a complete Android project that accesses an RSS feed and then displays the feed in a list view.
There still seems to be a lot of people interested in this - so if you are looking for an Android 3.0+ with fragments/async tasks etc, as well as complete application code, I have updated the posts again, and they can be found here!
You can download and check my project on google-play.
This project is about some turkish sport channels feeds. Lots of channels are in one application.
You can check source code of project on github.
Parse this type of Rss Feeds easily using XmlPullParser
public class RSSParser {
public static ArrayList<Pojo> getParserData(String Data){
try {
RSSXMLTag currentTag = null;
ArrayList<Pojo> postDataList = new ArrayList<>();
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(Data));
int eventType = xpp.getEventType();
Pojo pdData = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEEE, DD MMM yyyy ");
while (eventType != XmlPullParser.END_DOCUMENT) {
int i = 0;
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
pdData = new Pojo();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
} else if (xpp.getName().equals("creator")) {
currentTag = RSSXMLTag.CREATOR;
} else if (xpp.getName().equals("category")) {
currentTag = RSSXMLTag.CATEGORY;
} else if (xpp.getName().equals("description")) {
currentTag = RSSXMLTag.DESCRIPTION;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
Date postDate = dateFormat.parse(pdData.postDate);
pdData.postDate = dateFormat.format(postDate);
postDataList.add(pdData);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("debug", content);
if (pdData != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (pdData.postTitle != null) {
pdData.postTitle += content;
} else {
pdData.postTitle = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (pdData.postLink != null) {
pdData.postLink += content;
} else {
pdData.postLink = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (pdData.postDate != null) {
pdData.postDate += content;
} else {
pdData.postDate = content;
}
}
break;
case CATEGORY:
if (content.length() != 0) {
if (pdData.postCategory != null) {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
} else {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
}
}
break;
case DESCRIPTION:
if (content.length() != 0) {
if (pdData.postDescription != null) {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription += string;
} else {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription = string;
}
}
break;
case CREATOR:
if (content.length() != 0) {
if (pdData.postCreator != null) {
pdData.postCreator += content;
} else {
pdData.postCreator = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
return postDataList;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public enum RSSXMLTag {
IGNORETAG, TITLE, LINK, DATE,CREATOR,CATEGORY, DESCRIPTION;
}
public class Pojo {
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostLink() {
return postLink;
}
public void setPostLink(String postLink) {
this.postLink = postLink;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostCategory() {
return postCategory;
}
public void setPostCategory(String postCategory) {
this.postCategory = postCategory;
}
public String getPostDescription() {
return postDescription;
}
public void setPostDescription(String postDescription) {
this.postDescription = postDescription;
}
public String getPostCreator() {
return postCreator;
}
public void setPostCreator(String postCreator) {
this.postCreator = postCreator;
}
public String postTitle;
public String postLink;
public String postDate;
public String postCategory;
public String postDescription;
public String postCreator;
}
}

Categories

Resources