Standard Xml parser in android - android

Is there a standard xml parser in android, where i can put any standard link for the RSS and it will give me the result? i found an example but i must specify the path for the items.
Some thing like this link
http://www.rssboard.org/files/sample-rss-2.xml
try {
URL conn = new URL("http://www.rssboard.org/files/sample-rss-2.xml");
XmlParserHelper helper = new XmlParserHelper(conn.openStream(), "rss");
final String TITLES = "language";
XmlParseObject object = helper.createObject(TITLES, "//channel//item//title");
object.setParseAttributes();
object.setParseContent();
Map<String, List<XmlObject>> results = helper.parse();
List<XmlObject> titlesList = results.get(TITLES);
for (XmlObject title : titlesList) {
Log.d("Guid:", title.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
public class XmlParserHelper
{
protected String mRootName = "";
protected InputStream mXmlStream = null;
protected List<XmlParseObject> mParseList = new ArrayList<XmlParseObject>();
/**
* Initialize xml helper with file stream
* #param xmlStream input xml stream
*/
public XmlParserHelper(InputStream xmlStream, String rootName)
{
this.mXmlStream = xmlStream;
this.mRootName = rootName;
}
/**
* Point parse all attributes for XPath
* #param objectName key for attributes list in response
* #param XPath path to tag
*/
public void createAttributesObject(String objectName, String XPath)
{
XmlParseObject currentObject = new XmlParseObject(objectName, XPath);
currentObject.setParseAttributes();
mParseList.add(currentObject);
}
public void createContentObject(String objectName, String XPath)
{
XmlParseObject currentObject = new XmlParseObject(objectName, XPath);
currentObject.setParseContent();
mParseList.add(currentObject);
}
public XmlParseObject createObject(String objectName, String XPath)
{
XmlParseObject currentObject = new XmlParseObject(objectName, XPath);
mParseList.add(currentObject);
return currentObject;
}
public Map<String, List<XmlObject>> parse() throws Exception
{
if (mRootName.equals(""))
{
throw new Exception("Root tag must be defined");
}
RootElement root = new RootElement(mRootName);
for (XmlParseObject parselable : mParseList)
{
parselable.configurateListenersForRoot(root);
}
try {
Xml.parse(mXmlStream, Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
Map<String, List<XmlObject>> result = new HashMap<String, List<XmlObject>>();
for (XmlParseObject parselable : mParseList)
{
result.put(parselable.getName(), parselable.getResults());
}
return result;
}
}

URL url = new URL("http://www.rssboard.org/files/sample-rss-2.xml");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(url.openConnection().getInputStream(), "UTF_8");
//xpp.setInput(getInputStream(url), "UTF-8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Modify the above according to your needs. I have used a XmlPullParser.

Related

how to parse list of xml data from url in spinner android studio

i want to parse xml data in spinner, i already make a getter and setter for the data, here is xml data that i get from URL,
<response>
<result>
<foods>
<food>
<id>01</id>
<name>Pizza</name>
<price>20</price>
</food>
</foods>
</result>
</response>
how to parse list of XML data in spinner?
First of all, create a POJO class for food:
public class Food {
public String id, name, price;
}
private void parseXML(String urlResponse) {
XmlPullParserFactory parserFactory;
try {
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
InputStream is = new ByteArrayInputStream(urlResponse.getBytes());
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
processParsing(parser);
} catch (XmlPullParserException e) {
} catch (IOException e) {
}
}
private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
ArrayList<Food> foods = new ArrayList<>();
int eventType = parser.getEventType();
Food currentFood = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String eltName = null;
switch (eventType) {
case XmlPullParser.START_TAG:
eltName = parser.getName();
if ("food".equals(eltName)) {
currentFood = new Food();
foods.add(currentFood);
} else if (currentFood != null) {
if ("name".equals(eltName)) {
currentFood.name = parser.nextText();
} else if ("id".equals(eltName)) {
currentFood.id = parser.nextText();
} else if ("price".equals(eltName)) {
currentFood.price = parser.nextText();
}
}
break;
}
eventType = parser.next();
}
printFoods(foods);
}

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.

Get a Number from a String with substring() is no working

I want to get an Number from a String.
My Code for this Class is:
The XML is download correct, it founds my Value String but i get not the number from the String.
public class XMLProcessor extends AsyncTask<String, Void, String> {
private String rssURL;
private PostParserDelegate delegate;
private ArrayList<Post> posts;
String euro;
private StringBuilder buffer;
TextView mxntoeur;
TextView eurtomxn;
public XMLProcessor(String rssURL, PostParserDelegate delegate) {
this.rssURL = rssURL;
this.delegate = delegate;
posts = new ArrayList<Post>();
}
#Override
protected String doInBackground(String... strings) {
buffer = new StringBuilder();
try {
URL url = new URL(rssURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// HTTP Status "OK" -> HTTPCODE 200
int httpResponse = httpURLConnection.getResponseCode();
if ( httpResponse != 200) {
throw new Exception("Fehlercode: " + httpResponse);
}
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int charactersRead;
char[] tmpChars = new char[400];
while (true) {
charactersRead = reader.read(tmpChars);
if (charactersRead <= 0) {
break;
}
buffer.append(String.copyValueOf(tmpChars, 0, charactersRead));
}
return buffer.toString();
} catch (Exception e) {
Log.e("XMLProcessor", e.getMessage());
Log.e("XMLProcessor", e.getStackTrace().toString());
}
return String.valueOf(0);
}
#Override
protected void onPostExecute(String aDouble) {
super.onPostExecute(aDouble);
parse();
}
protected void parse()
{
String rawXML = buffer.toString();
Post aPost = null;
boolean isProcessingItem = false;
String innerValue ="";
try {
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setInput(new StringReader(rawXML));
int event = parser.getEventType();
while (event !=XmlPullParser.END_DOCUMENT)
{
String tag = parser.getName();
switch ( event) {
case XmlPullParser.START_TAG:
if (tag == "item" ) {
Log.d("XMLProcessor", "Neuer Post!");
isProcessingItem = true;
aPost = new Post();
}
break;
case XmlPullParser.TEXT:
innerValue = parser.getText();
break;
case XmlPullParser.END_TAG:
if (isProcessingItem){
if (tag == "item") {
posts.add(aPost);
isProcessingItem = false;
}
} else if ( tag == "description") {
aPost.setPesoInEuro(innerValue);
euro = new String(innerValue.substring(13,21));
//euro = innerValue.substring(13,21);
eurtomxn.setText(euro);
}
break;
}
event = parser.next();
}
delegate.xmlFeedParsed(posts);
} catch (Exception e) {
Log.e("XMLProcess", e.getStackTrace().toString());
}
}
}
In innerValue i get the Correct Sting what i need
/n 1.00 EUR = 21.90612 MXN<br/>\n 1.00 MXN = 0.04565 EUR<br/>\n
Converter--\n
<a href="http://eur.de.fxexchangerate.com/mxn-exchange-rates-history.html">Historische
</a>
\n.
But my problem is, that i need this Number 21.90612. I have try it with substring(13,21), but it was no working.
Have you a idea, how i can fix my problem?
Thank you
It's not very clear what exactly is the Problem, it would be useful if you show the Exception!
Have you checked if the String innerValue has a valid lenght?
if(innerValue.lenght() >= 21){euro = innerValue.substring(13,21);} else {/* Do something here!*/}
}

how to consume data in rest api that returns xml data in android

please can anybody tell how to consume rest API in android that returns xml data.there are so many example with JSON.but I need to response in xml format ...can anybody tell how to do that please help me thanks in advance.
You can try something like this
private class CallAPI extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String schid="";
String resultToDisplay = "";
InputStream in = null;
Result result = null ;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
//resultToDisplay +="&" + URLEncoder.encode("data", "UTF-8") ;
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
// Parse XML
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
result = parseXML(parser);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Simple logic to determine if the email is dangerous, invalid, or valid
if (result != null ) {
if( result.hygieneResult.equals("Spam Trap")) {
resultToDisplay = "Dangerous, please correct";
}
else if( Integer.parseInt(result.statusNbr) >= 300) {
resultToDisplay = "Invalid, please re-enter";
}
else {
resultToDisplay = "Thank you for your submission";
}
}
else {
resultToDisplay = "Exception Occured";
}
return resultToDisplay;
}
protected void onPostExecute(String schid) {
if(schid == null) {
schid = "THERE WAS AN ERROR";
}
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra(EXTRA_MESSAGE, schid);
startActivity(intent);
}
private Result parseXML( XmlPullParser parser ) throws XmlPullParserException, IOException {
int eventType = parser.getEventType();
Result result = new Result();
while( eventType!= XmlPullParser.END_DOCUMENT) {
String strid = null;
switch(eventType)
{
case XmlPullParser.START_TAG:
strid = parser.toString();
//name=parser.getName();
if( strid.equals("Error")) {
System.out.println("Web API Error!");
}
else if ( strid.equals("StatusNbr")) {
result.statusNbr = parser.nextText();
}
else if (strid.equals("HygieneResult")) {
result.hygieneResult = parser.nextText();
}
break;
case XmlPullParser.END_TAG:
break;
} // end switch
eventType = parser.next();
} // end while
return result;
}
} // end CallAPI
Now in your activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// This is the method that is called when the submit button is clicked
public void verifyDetails(View view) {
EditText schidEditText = (EditText) findViewById(R.id.sch_id);
String schid = schidEditText.getText().toString();
if( schid != null && !schid.isEmpty()) {
String urlString = apiURL + "schid:" + schid.toString();
//String urlString = apiURL + "LicenseInfo.RegisteredUser.UserID=" + strikeIronUserName + "&LicenseInfo.RegisteredUser.Password=" + strikeIronPassword + "&VerifyEmail.Email=" + email + "&VerifyEmail.Timeout=30";
new CallAPI().execute(urlString);
}
}
}
You need to use DocumentBuilderFactory for Parsing XML using Java
You can find a good tutorial for this on that place XML and Java - Parsing XML using Java
Check Xml Parsing Tuotorial using DOM parser
also Xml Parsing Tuotorial using XML pull parser

Android XML Parser only getting last entry

I'm trying to Parse an XML file into a List, however it is only getting the last entry in the XML file. I have a sample below
<?xml version="1.0"?>
<stops>
<stop>
<number>stop_code</number>
<lat>stop_lat</lat>
<lon>stop_lon</lon>
<name>stop_name</name>
</stop>
<stop>
<number>112112</number>
<lat> 51.060931</lat>
<lon>-114.065158</lon>
<name>"CRESCENT HEIGHTS HIGH SCHOOL"</name>
</stop>
<stop>
<number>2110</number>
<lat> 51.082803</lat>
<lon>-114.214888</lon>
<name>"EB CAN OLYMPIC RD#OLYMPIC CE ENTR"</name>
</stop>
.....
<stop>
<number>9988</number>
<lat> 51.047388</lat>
<lon>-114.067770</lon>
<name>"NB 2 ST#6 AV SW"</name>
</stop>
<stop>
<number>9998</number>
<lat> 50.997509</lat>
<lon>-114.013415</lon>
<name>"19 St # 62 Ave SE nb ns"</name>
</stop>
And my pull parser is
ublic class PullParser {
public static final String STOP_NAME = "name";
public static final String STOP_LAT = "lat";
public static final String STOP_LON = "lon";
public static final String NUMBER = "number";
private Stops currentStop = null;
private String currentTag= null;
List<Stops> stops = new ArrayList<Stops>();
public List<Stops> parseXML (Context context) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
InputStream stream = context.getResources().openRawResource(R.raw.stops_xml);
xpp.setInput(stream,null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
handleStartTag(xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
currentTag = null;
} else if (eventType == XmlPullParser.TEXT) {
handleText(xpp.getText());
}
eventType = xpp.next();
}
} catch (Resources.NotFoundException e) {
Log.d(MainActivity.TAG, e.getMessage());
} catch (XmlPullParserException e) {
Log.d(MainActivity.TAG, e.getMessage());
} catch (IOException e) {
Log.d(MainActivity.TAG, e.getMessage());
}
return stops;
}
private void handleText(String text) {
String xmlText = text;
if (currentStop != null && currentTag != null) {
if (currentTag.equals(STOP_NAME)) {
currentStop.setName(xmlText);
}
else if (currentTag.equals(STOP_LAT)) {
currentStop.setLat(xmlText);
}
else if (currentTag.equals(STOP_LON)) {
currentStop.setLon(xmlText);
}
else if (currentTag.equals(NUMBER)) {
currentStop.setNumber(xmlText);
}
}
}
private void handleStartTag(String name) {
if (name.equals("stop")) {
currentStop = new Stops();
stops.add(currentStop);
}
else {
currentTag = name;
}
}
}
When I run this it only returns a stop number of 9998 for all 5882 entries (That is the correct number of entries in the file). Any thing obvious that I'm missing?
MyXmlPullParser objMyXmlPullParser = new MyXmlPullParser(context);
List<Map<String , String>> list = objMyXmlPullParser.readXml("Xml respose put here", "Table");
public class MyXmlPullParser
{
Context _context ;
public MyXmlPullParser(Context _context)
{
this._context = _context ;
}
public List<Map<String , String>> readXml(String XmlString , String ParentTag)
{
Map<String , String > map = new HashMap<String, String>();
List<Map<String , String >> list = new ArrayList<Map<String , String >>();
try
{
String Tag = "" ;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader (XmlString));
int eventType = xpp.getEventType();
while (true)
{
if(eventType == XmlPullParser.START_TAG)
{
Tag = xpp.getName();
}
else if(eventType == XmlPullParser.END_TAG)
{
Tag = "" ;
if(xpp.getName().equals(ParentTag))
{
list.add(map);
map = new HashMap<String, String>();
}
}
else if(eventType == XmlPullParser.TEXT)
{
String text = xpp.getText();
if(!Tag.equals("") && !Tag.equals(ParentTag))
{
map.put(Tag, text);
}
}
else if(eventType == XmlPullParser.END_DOCUMENT)
{
System.out.println("End document");
break ;
}
eventType = xpp.next();
}
}
catch (XmlPullParserException e)
{
Log.e("xml reader" , "error in parsing xml");
return null ;
}
catch (IOException e)
{
Log.e("xml reader" , "error in IO in xml");
return null ;
}
return list ;
}
Hope it may helps you

Categories

Resources