Error when fetching a second XML from the web - android

im new to android development and im trying to build my first app which looks for a online generated xml file to display information. In the first activity i created a ListView with all the entries from an XML file, as soon as i click on an entry it passes the id and goes to the 2nd activity which should access another XML file with the details. However i keep getting this error when trying to fetch the XML for the details:
java.lang.ClassCastException:
org.apache.harmony.xml.dom.ElementImpl
Any ideas whats wrong? Here is the source for the "details" activity:
package en.android.itleaked.com;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.sax.Element;
import android.widget.ImageView;
import android.widget.TextView;
public class showReleases extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.releasedetails);
getFeed();
}
public void getFeed() {
Bundle extras = getIntent().getExtras();
try {
URL url2 = new URL("http://www.it-leaked.com/app/details.php?id=" + extras.getString("id"));
DocumentBuilderFactory dbf2 = DocumentBuilderFactory.newInstance();
DocumentBuilder db2 = dbf2.newDocumentBuilder();
Document doc2 = db2.parse(new InputSource(url2.openStream()));
doc2.getDocumentElement().normalize();
NodeList nodeList2 = doc2.getElementsByTagName("item");
String relTitle[] = new String[nodeList2.getLength()];
String relCover[] = new String[nodeList2.getLength()];
for (int i = 0; i < nodeList2.getLength(); i++) {
Node node2 = nodeList2.item(i);
Element fstElmnt2 = (Element) node2;
NodeList nameList2 = ((Document) fstElmnt2).getElementsByTagName("title");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = ((Node) nameElement2).getChildNodes();
relTitle[i] = ((Node) nameList2.item(0)).getNodeValue();
NodeList coverList2 = ((Document) fstElmnt2).getElementsByTagName("cover");
Element coverElement2 = (Element) coverList2.item(0);
coverList2 = ((Node) coverElement2).getChildNodes();
relCover[i] = ((Node) coverList2.item(0)).getNodeValue();
}
TextView txtView = (TextView)findViewById(R.id.TextView01);
txtView.setText(relTitle[0]);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
Drawable drawable = LoadImageFromWebOperations(relCover[0]);
imgView.setImageDrawable(drawable);
}
catch (Exception e) {
TextView txtView2 = (TextView)findViewById(R.id.TextView02);
txtView2.setText("Error: " + e);
}
}
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
Here is the URL for the XML with an attached id so you can see what it looks like:
http://www.it-leaked.com/app/details.php?id=50969
Any ideas whats going on? By the way i added the number 2 to every variable which has something to do with the XML parsing / fetching just to make sure theres no conflict with the other activity, but im still getting the same error..
I hope you can help me out.
Thanks in advance

This question is a little old but I believe the ClassCastException is due to attempting to cast the elements in the nodelist to android.sax.Element type rather than org.w3c.dom.Element; check the imports.

Looking at your exception (which is java.lang.ClassCastException) the problem is in casting some class to another.
In your code i didn't understand the reason casting Element to Document - Element has getElementsByTagName method which you are using. Look here: http://developer.android.com/reference/org/w3c/dom/Element.html
It is the root of all evil. Element and Document both implementing Node interface, but Document isn't implements Element - that's why Element can't be cast to Document.
Anyway, expcetion line number can determine the exact error position.

Related

Parsing specific texts using Jsoup

I have a cities.txt file placed in my res/raw folder. Inside it contains the following.
<div class="state">Alabama</div>
<ul><li>auburn</li>
<li>birmingham</li> </ul>
<div class="state">Alaska</div>
<ul><li>anchorage</li>
<li>fairbanks</li></ul>
<div class="state">Arizona</div>
<ul><li>flagstaff</li>
<li>mohave county</li></ul>
I want to grab the cities for the state Alabama and display it on a ListView. The ouput should be like this.
auburn
birmingham
My current code grabs all the six cities and displays them on the ListView instead. This is my code.
package com.example.readfile;
import java.io.InputStream;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Cities extends Activity {
ListView listUSCities;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.city_layout);
listUSCities = (ListView) findViewById(R.id.listcities);
new MyTask().execute();
}
class MyTask extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> arr_linkText = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document doc;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.cities);
byte[] b = new byte[in_s.available()];
in_s.read(b);
// Parsing using Jsoup starts here
doc = Jsoup.parse(new String(b));
// Parsing the states
Elements links = doc.select("div");
for (Element link : links) {
if (link.text().contains("Alabama")) {
// Extracting the cities
Elements cities = doc.select("a");
for (Element city : cities) {
arr_linkText.add(city.text());
}
}
}
} catch (Exception e) {
// e.printStackTrace();
}
return arr_linkText; // << retrun ArrayList from here
}
#Override
protected void onPostExecute(ArrayList<String> result) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
Cities.this, android.R.layout.simple_list_item_1,
android.R.id.text1);
for (String temp_result : result) {
adapter.add(temp_result);
}
listUSCities.setAdapter(adapter);
}
}
}
How can I extract the cities only for that specified state?
How do I stop parsing the file after I extracted the cities to optimize speed?
The actual cities.txtcontains more information, I only provided a sample. I will appreciate your help. Thank you!
// Parsing the states
Elements links = doc.select("div");
for (Element link : links) {
if (link.text().contains("Alabama")) {
// Extracting the cities
Elements cities = link.select("a");//<- 'doc' is the whole doc, link is your state.
for (Element city : cities) {
arr_linkText.add(city.text());
}
break;//breaks off the loop, since you have found what you want.
}
}
That is an odd structure for an HTML document. The <div> is used just for the header, and the list is off by itself. Seeing as you trimmed the actual document, this may or may not work. The elements you are after are in the ul element following your div, so you need to go to the next sibling and search there. This will only work if there are no other elements between your div and ul elements.
Elements links = doc.select("div");
for (Element link : links) {
if (link.text().contains("Alabama")) {
// Extracting the cities in the list that is next in the DOM
Elements cities = link.nextElementSibling().select("a");
for (Element city : cities) {
arr_linkText.add(city.text());
}
}
}

How do I display the JSON results from UrbanDictionary in my app?

I'm working on an app that simply has to go out to UrbanDictionary and return the results of a word search in JSON format...then display it in an Android project.
Here is my code in its entirety:
package org.twodee.mitchemc.webapi;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ListActivity {
private ArrayList<String> definitionsList;
private ArrayAdapter<String> adapter;
private EditText wordText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wordText = (EditText) findViewById(R.id.wordText);
Button defineButton = (Button) findViewById(R.id.defineButton);
definitionsList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, definitionsList);
setListAdapter(adapter);
defineButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = wordText.getText().toString();
new DownloadTask().execute(word);
}
});
}
private ArrayList<String> getDefs(String word) {
ArrayList<String> definitions = new ArrayList<String>();
try {
URL url = new URL("http://api.urbandictionary.com/v0/define?term="
+ word);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
String json = Utilities.slurp(in);
Log.d("FOO", json);
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
definitions.add(object.getString("definition"));
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return definitions;
}
class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... params) {
String word = params[0];
return getDefs(word);
}
#Override
protected void onPostExecute(ArrayList<String> defs) {
super.onPostExecute(defs);
definitionsList.clear();
definitionsList.addAll(defs);
adapter.notifyDataSetChanged();
}
}
}
Pay no attention to the Utilities.slurp behind the curtain.
So, if I run this, it doesn't crash, and it actually does give me results, but it throws them in LogCat...not my app. I previously found the following exception:
of type org.json.jsonarray cannot be converted to jsonobject
I looked over this forum and found the notion that I've got objects within an array (or something like that) but I can't figure out how to reflect that in code.
What I'd like to have happen is you type, say, "Hey" into the app, hit "Define" and then there's a list of definitions below it. Only the definitions...so the JSON part of it should be "definition"
Here's some JSON output that I get in LogCat. I hope this is readable:
12-06 19:00:57.647: W/System.err(1400): org.json.JSONException: Value {"total":32,"result_type":"exact","list":[{"thumbs_down":428,"author":"D.B. Echo","definition":"A contraction for \"Hello, I find you attractive and would like to dance with you, share some drinks with you, and then perhaps have sex with you. Nothing serious, of course, and I doubt that this will result in a long term relationship, but I would appeciate you considering my proposal.\"","permalink":"http:\/\/hey.urbanup.com\/1099714","thumbs_up":1530,"word":"hey","current_vote":"","example":"Guy at bar to attractive girl: \"Hey.\"\r\n\r\nAttractive girl to guy: \"Go to hell, creep.\" (Moves to other side of bar.)","defid":1099714},{"thumbs_down":250,"author":"Erica","definition":"hey is a way to say \"hi\" or \"what's up\"\r\nthe type of 'hey' horses eat is hAy you morons!!!","permalink":"http:\/\/hey.urbanup.com\/574637","thumbs_up":541,"word":"Hey","current_vote":"","example":"hey what's up!?!\r\nhorses eat hay!","defid":574637},{"thumbs_down":144,"author":"SoMe RaNdOm PeRsOn","definition":"I word to use to get someone's attention. Even if you don't know the persons name by simply saying \"hey\" you can easily get their attention","permalink":"http:\/\/hey.urbanup.com\/1106278","thumbs_up":294,"word":"hey","current_vote":"","example":"guy 1:Hey Alex what's that guys name over there?\r\nAlex: How the hell should I know?\r\nGuy 1: Hey!!\r\nMystery guy: ::looks around confused::\r\nGuy 1: O hi.","defid":1106278},{"thumbs_down":120,"author":"Jamesrob92","definition":"1. The most informal form of greeting. Usually used in a friendly manner or to sound cool and relaxed.\r\n2. An exclamation used to get someone's attention","permalink":"http:\/\/hey.urbanup.com\/2153666","thumbs_up":249,"word":"hey","current_vote":"","example":"1. Hey, what's up?\r\n2. HEY! Wait for me!\r\n3. HEY YOU! Get away from my wife!","defid":2153666},{"thumbs_down":133,"author":"marshmallow","definition":"a slang term used by many people in place of hello","permalink":"http:\/\/hey.urbanup.com\/1129122","thumbs_up":219,"word":"hey","current_vote":"","example":"Hey Ma...whats crackin?","defid":1129122},{"thumbs_down":79,"author":"hey malasadas","definition":"an expression used to get someone's attention","permalink":"http:\/\/hey.urbanup.com\/198491","thumbs_up":128,"word":"hey","current_vote":"","example":"hey man, what the hell are you doing?!","defid":198491},{"thumbs_down":54,"author":"HappyGirl1993","definition":"Considered to be a lot more flirtatious than 'hello' or 'hi.'","permalink":"http:\/\/hey.urbanup.com\/5302185","thumbs_up":68,"word":"Hey","current_vote":"","example":"Example...\n\nGuy: Hey.\r\nGirl: Hi.\r\nGuy: *Whoa, total FAIL!*","defid":5302185},{"thumbs_down":37,"author":"Eric Klein...","definition":"1. Interjection, an informal greeting. \r\n\r\n2. Verb, to 'hey' someone. The act of driving down public roads in a lane near a sidewalk, coming upon an unsuspecting pedestrian, and hollering \"HEY!\" as loudly as possible in their general direction. Most effective if done with all windows rolled down, and all members of the vehicle participating. (Originating in Sioux Falls, SD)","permalink":"http:\/\/hey.urbanup.com\/2705914","thumbs_up":42,"word":"Hey","current_vote":"","example":"1. \"Hey buddy, how's the syphilis?\"\r\n\r\n2. \"Jimmy and I heyed a kid so bad the other day, he fell off his bike!\"","defid":2705914},{"thumbs_down":80,"author":"J-Lib","definition":"a slang interjection or prompt often used in place of \"eh\" or \"right\" in order to make a sentence into a question; used in parts of Canada","permalink":"http:\/\/hey.urbanup.com\/1262450","thumbs_up":67,"word":"hey","current_vote":"","example":"It's supposed to snow tomorrow, hey?\r\nThat guy was pretty attractive, hey?","defid":1262450},{"thumbs_down":7,"author":"Bam Bam Branson","definition":"Why would you even search this?","permalink":"http:\/\/hey.urbanup.com\/5850424","thumbs_up":8,"word":"Hey","current_vote":"","example":"Hey is Idk","defid":5850424}],"pages":4,"sounds":["http:\/\/media.urbandictiona
Any help would be greatly appreciated! Thanks in advance!
UPDATE: Here's the code that works:
String json = Utilities.slurp(in);
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray("list");
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
definitions.add(object.getString("definition"));
}
Based on the json you get back from that request, you are setting up your JSONObject wrong. Here is an example of the json that comes back:
{
"has_related_words": true,
"result_type": "exact",
"list": [
{
"defid": 2957653,
"word": "test",
"author": "sm1g",
"permalink": "http://test.urbanup.com/2957653",
"definition": "To check if something coresponds the promised result or what effect does it have at all.",
"example": "By typing in the word \"test\" you prolly tried to search if there was a definition for this word.",
"thumbs_up": 123,
"thumbs_down": 46,
"current_vote": ""
}
],
"sounds": [
"http://media.urbandictionary.com/sound/test-8076.mp3"
],
"total": 20,
"pages": 2
}
In your code, to grab an array like list, you would need to do:
String json = Utilities.slurp(in);
JSONObject jsonObject = new JSONObject(json);
//now get the list array
JSONArray list = new JSONArray(jsonObject.getArray("list"));
The method names may not be exact.

Xml Parse in Android:: using DOM

I am new to android, I tried XML parse with SAX previously but I got Exception in Network,I tried lot with that , But not able to get that, many suggest to use AsyncTask, I tried with that , But again failed, So I tried with DOM now, Again same got some exception in android.os.NetworkOnMainThreadException and gralloc_goldfish error (i.e) Emulator without GPU emulation detected .... help me for this problem. i gng this program for 2 days
Program::XMLParsingDOMExample.java
package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingDOMExample extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** 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 name[];
TextView website[];
TextView category[];
try {
URL url = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
/** Assign textview array lenght by arraylist size */
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Set the layout view to display */
setContentView(layout);
}
}
example.xml
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
i m not able to get output for the above code.. got some exception in android.os.NetworkOnMainThreadException and gralloc_goldfish error (i.e) Emulator without GPU emulation detected .... help me for this problem. i gng this program for 2 days.. Thank in advance
Execute this on a background thread (maybe using an AsyncTask).
A NetworkOnMainThreadException means exactly this - you are running a network call on the main UI thread. This is to encourage us to not make calls that block UI interaction.
url.openStream() is what triggers this.

Retreivent attribute value from XPath in android

I have the following XML retreived from webservices.How do i get the value of StructureTransID i.e(254) from the above XML using XPath in android? Can anyone help me on this.
<Response>
−
<NewDataSet>
−
<EnrollmentList>
<Transaction_ID>369</Transaction_ID>
<Transaction_Key>489</Transaction_Key>
<Transaction_Type>ENROLLMENT_INFO</Transaction_Type>
<Corp_ID>2</Corp_ID>
−
<Transaction_Xml>
<EnrollmentInfo><SelectedPackages><Package Id="1-GQGFWG" Category="Medical" CoverageLevel="EMP_CHILDREN" CoverageAmt="355.11" TotalCoverageAmt="710.22" StructureTransID="254" EffectiveDate="01/01/2012" TerminationDate="12/31/2012" /></SelectedPackages><PersonalInfo><EmployeeID>E0211</EmployeeID><FirstName>Michael</FirstName><MiddleName /><LastName>Keaton</LastName><DateOfBirth>10/21/1975</DateOfBirth><Gender>M</Gender><SSN>123456789</SSN><Email>mkeaton#designllc.com</Email><AddressLine1>33 Park Street</AddressLine1><AddressLine2 /><AddressLine3 /><City>Jacksonville</City><State>FL</State><ZipCode>32220</ZipCode><HomePhone>(111) 222-4444</HomePhone><WorkPhone>(913) 244-8188</WorkPhone><Dependents><Dependent><FirstName>Alisha</FirstName><MiddleName /><LastName>Jones</LastName><DateOfBirth>1/13/2009</DateOfBirth><Gender>F</Gender><Relationship>Dependent</Relationship><AddressLine1>33 Park Street</AddressLine1><AddressLine2 /><AddressLine3 /><City>Jacksonville</City><State>FL</State><ZipCode>32220</ZipCode><HomePhone /><MedicareNumber /><PartA_EffectiveDate /><PartB_EffectiveDate /><IsFullTimeStudent>False</IsFullTimeStudent><CollegeName /><ExpectedGraduationDate /><CreditHours /></Dependent></Dependents></PersonalInfo><WorkInfo><Class>A004</Class><DateOfHire>05/01/2010</DateOfHire><Designation>Associate</Designation><WorkLocation>Canton</WorkLocation></WorkInfo><SelectedPackages /></EnrollmentInfo>
</Transaction_Xml>
<Active_Ind>1</Active_Ind>
<Effective_Date>2012-01-01T00:00:00+05:30</Effective_Date>
<Status>CO</Status>
<Created_On>2011-12-20T00:47:20.187+05:30</Created_On>
<Created_By>msmith</Created_By>
<Modified_On>2012-02-10T17:50:15.647+05:30</Modified_On>
<Modified_By>mkeaton</Modified_By>
<Termination_Date>2012-12-31T00:00:00+05:30</Termination_Date>
<Comments>Change in employment status</Comments>
<Task_ID>636</Task_ID>
<User_ID>489</User_ID>
<Import_ID>476</Import_ID>
<Corp_ID1>2</Corp_ID1>
<Employee_ID>E0211</Employee_ID>
<Login>mkeaton</Login>
<Password>cGFzc3dvcmQ=</Password>
<Full_Nm>Michael Keaton</Full_Nm>
<First_Nm>Michael</First_Nm>
<Middle_Nm/>
<Last_Nm>Keaton</Last_Nm>
<DOB>1975-10-21T00:00:00+05:30</DOB>
<Address_1>33 Park Street</Address_1>
<Address_2/>
<Address_3/>
<City>Jacksonville</City>
<State>FL</State>
<Postal_Code>32220</Postal_Code>
<Home_Phone_No>(111) 222-4444</Home_Phone_No>
<Work_Phone_No>(913) 244-8188</Work_Phone_No>
<Cell_Phone_No/>
<Email_Addr>mkeaton#designllc.com</Email_Addr>
<Login_Attempts_Cnt>0</Login_Attempts_Cnt>
<Login_Locked_Ind>0</Login_Locked_Ind>
<Allow_Internet_Use>1</Allow_Internet_Use>
<Active_Ind1>1</Active_Ind1>
<Hired_Dt>2010-05-01T00:00:00+05:30</Hired_Dt>
<Designation>Associate</Designation>
<Work_Location>Canton</Work_Location>
<SubGroup_ID>0001</SubGroup_ID>
<Created_On1>2011-12-20T00:44:04.577+05:30</Created_On1>
<Created_By1>msmith</Created_By1>
<Modified_On1>2012-02-10T17:50:10.343+05:30</Modified_On1>
<Modified_By1>mkeaton</Modified_By1>
<SSN>123456789</SSN>
<Class>A004</Class>
<Status1>A</Status1>
<EULA>1</EULA>
<Gender>M</Gender>
<ReAssignedToCobra>false</ReAssignedToCobra>
<ClassDesc>A004 - Management</ClassDesc>
</EnrollmentList>
</NewDataSet>
</Response>
I have tried this code in Java it works fine,but the same concept does not retreive the value in android.
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XML {
private NodeList nodelist;
private static Element ele;
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
builder = factory.newDocumentBuilder();
doc = builder.parse("/home/stella/person.xml");
ele = doc.getDocumentElement();
XPathFactory factor = XPathFactory.newInstance();
XPath xpath = factor.newXPath();
XPathExpression expr = xpath.compile("//Package");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++)
{
Node currentItem = nodes.item(i);
String key = currentItem.getAttributes().getNamedItem("StructureTransID").getNodeValue();
String value = currentItem.getTextContent();
System.out.printf("%1s = %2s\n", key, value);
}
}
}
I copied your XML file to Notepad and tried to save it but it reported that "This file contains characters in Unicode format which will be lost if you save this file as an ANSI encoded text file.". I let it proceed and then copied your program to a new Android project and it works! i.e. it does load your XML file and extract the "254" value.
I then went back to the XML file and attempted to identify the weird characters and it led me to the 3 characters that look like minus signs, located at:
<Response>
−
<NewDataSet>
−
...
−
<Transaction_Xml>
...
This got me to think that these characters aren't minus signs, but, perhaps some weird encoding which is preventing it from working with the XML parser on Android. These characters, if correct, may need to be edited or migrated to an encoding that works with Android, perhaps UTF-8?
Anyhow, I think this should give enough pointers on where to look.

Android : Reading XML from local resource (for testing)

I'm writing an app which will read XML from a webservice (probably via kSOAP2). I'm fairly happy with SAX parsing, as I've done XML parsing iPhone apps.
Unfortunately the webservice isn't public yet so for initial testing I have some files containing the XML I need to parse. In this early dev phase I just need to read the XML from the files and pass it into the XML parser
Xml.parse(this.testXML, root.getContentHandler());
How do I read the XML from a file/resource into a string to pass into this method. I want to crack on and test the parser, but this simple step is holding me up.
Thanks
Create a raw folder under res
Put your XML file in there, eg. testXML.xml:
/res/raw/testXML.xml
You should be able to use your XML parser using that as an inputstream:
Xml.parse(getResources().openRawResource(R.raw.testXML), Xml.Encoding.UTF_8, root.getContentHandler());
Try that.
I found a solution. Using Assets.
Here is the simple code example of how I did it.
I know I could have used XmlPullParser to simply load an xml file from res, but I wanted to use SAX parsing. This allows me to simply throw an XML string into the SAX parser for testing before I plug in the webservice.
It just uses a simple view with a Button to kick off the file load and a TextView to display the XML for now. I can get on with my parser :)
package com.martins.XmlParserTest
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
Button btn;
TextView tvXml;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Load XML for parsing.
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("textxml.xml");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
String s = readTextFile(inputStream);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(s);
}
});
}
private String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
}
Raises exception due to incorrectly formed XML (line1,Pos0).
You tell parser that the encoding is UTF-8 and if it isn't you may get various errors (depending on parsers). If you are using non-xml editor to edit your XML it may save the file in a different encoding regardless what you declared it to be in the XML document.

Categories

Resources