XML parsing for complex xml - android

Actually i try to do xml parsing from my local host and retrieve the value into the spinner.
what my doubt is i also need to retrieve the value inside the attribute which was present inside the book node (i,e) . I refer many tutorials and source codes still i cant able to do it. Any one please help to do it. Thanks in advance.
XML Structure
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>
An in-depth look at creating applications with XML.
</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>
A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.
</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>
After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.
</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>
In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.
</description>
</book>
</catalog>
Java code
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
ArrayList<String> title;
Button button;
Spinner spinner;
ArrayAdapter<String> from_adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = new ArrayList<String>();
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
parse();
from_adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item, title);
from_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(from_adapter);
}
});
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(), ""+spinner.getSelectedItem().toString().trim(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://10.0.2.2/book.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element idElmnt = (Element) node;
NodeList idList = idElmnt.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("title");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("genre");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("price");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) idList.item(0)).getNodeValue()+":"+((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}

try this code inside for loop.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value=node.getNodeValue();// you can store this in array for all nodes
Element idElmnt = (Element) node;
NodeList idList = idElmnt.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("title");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("genre");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("price");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) idList.item(0)).getNodeValue()+":"+((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}

Related

How I can insert data in a String from registerReceiver (Service) ? Android

How I can insert data in a String from registerReceiver, I have below codes .
In my Service I writed this code :
Intent ir=new Intent();
ir.setAction(MY_ACTION);
ir.putExtra("Webresponse", Webresponse);
sendBroadcast(ir);
And in Activity I get data :
private class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
String datapassed = arg1.getStringExtra("Webresponse");
Toast.makeText(ChatPage.this,
"Triggered by Service!\n"
+ "Data passed: " + datapassed,
Toast.LENGTH_LONG).show();
}
}
Then in onCreate I can get data and see data with Toast but I need that insert data in a String value:
MyReceiver m = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ChatPage_Service.MY_ACTION);
registerReceiver(m, intentFilter);
I need to :
String values = registerReceiver(m, intentFilter);
If you are fill a ListView you should fill it in your private class MyReceiver extends BroadcastReceiver .
For example this is my code :
private class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
datapassed = arg1.getStringExtra("Webresponse");
try {
XmlToDocument xmltodoc = new XmlToDocument();
Document doc = xmltodoc.getDomElement(datapassed);
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfPersons = doc
.getElementsByTagName("user");
adapter.clear();
for (int s = 0; s < listOfPersons.getLength(); s++) {
StructPasokhgoo stp = new StructPasokhgoo();
Node firstPersonNode = listOfPersons.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList ageList = firstPersonElement
.getElementsByTagName("group");
Element ageElement = (Element) ageList
.item(0);
NodeList textAgeList = ageElement
.getChildNodes();
group = ((Node) textAgeList.item(0))
.getNodeValue().trim();
if (group.equals("admin")) {
//----//
NodeList firstNameList = firstPersonElement
.getElementsByTagName("id");
Element firstNameElement = (Element) firstNameList
.item(0);
NodeList textFNList = firstNameElement
.getChildNodes();
id = ((Node) textFNList.item(0))
.getNodeValue().trim();
//----//
NodeList lastNameList = firstPersonElement
.getElementsByTagName("name");
Element lastNameElement = (Element) lastNameList
.item(0);
NodeList textLNList = lastNameElement
.getChildNodes();
name = ((Node) textLNList.item(0))
.getNodeValue().trim();
stp.NameS = name;
stp.Group = group;
stp.IdS = id;
pasokhgo.add(stp);
}
if (group.equals("user")) {
//----//
NodeList firstNameList = firstPersonElement
.getElementsByTagName("id");
Element firstNameElement = (Element) firstNameList
.item(0);
NodeList textFNList = firstNameElement
.getChildNodes();
idTwo = ((Node) textFNList.item(0))
.getNodeValue().trim();
//----//
NodeList lastNameList = firstPersonElement
.getElementsByTagName("name");
Element lastNameElement = (Element) lastNameList
.item(0);
NodeList textLNList = lastNameElement
.getChildNodes();
nameTwo = ((Node) textLNList.item(0))
.getNodeValue().trim();
//----//
stp.NameE = nameTwo;
stp.Group = group;
stp.IdE = idTwo;
pasokhgo.add(stp);
}
}
}
adapter.notifyDataSetChanged();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
I had this problem and I can't get data in activity same you I can see just toast but then i fill listView in MyReceiver.class.

android xml parsing does not show results?

I am newbie to android, I am trying to parse xml data from http://www.astrology.com/horoscopes/daily-horoscope.rss, I grab the code from
How can I parse xml from url in android? here, I used sherLock library, I also set internet permissions in manifest, but still unable to grab it, here is the same code except a little modification,
protected 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.astrology.com/horoscopes/daily-horoscope.rss");
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 = ((Document) fstElmnt).getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = ((Node) nameElement).getChildNodes();
name[i].setText("Name = " + ((Node) nameList.item(0)).getNodeValue());
//category[i].setText("Website Category = " + ((org.w3c.dom.Element) 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);
}
Remember I am extending my MainActivity class from SherlockActivity, when I execute the code, only action bar appears!

how to use listView with parsed strings in Android?

Here is my code. I want to see these parsed strings into ListView in Android. How can I do this?
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
System.out.println("Name: " + getCharacterDataFromElement(line));
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}

Why don't I get Views?

I have the next code
ProgressDialog pd;
LinearLayout layout;
ListView listview;
TextView name[];
TextView website[];
/** Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pd = ProgressDialog.show(this,
"Title",
"Message",
true, false);
new Thread(new Runnable(){
public void run(){
begin();
pd.dismiss();
}
}).start();
}
public void begin(){
Calendar c = Calendar.getInstance();
String dia2,mes2;
mes2="0";
int dia = c.get(Calendar.DAY_OF_MONTH);
int mes = c.get(Calendar.MONTH);
try {
URL url = new URL(
"http://www.tudiscovery.com/dni-tvlistings/GetScheduleByBroadcastDate?type=day&country_code=LTM&channel_code=DCLA-SP&date="+ dia2 +""+ mes2 +"2012");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("programme");
/** Assign textview array lenght by arraylist size */
name = new TextView[nodeList.getLength()];
website = 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);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("series-title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Programa = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("raw");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Hora = "
+ ((Node) websiteList.item(0)).getNodeValue().subSequence(0, 2) +":" + ((Node) websiteList.item(0)).getNodeValue().subSequence(2, 4));
name[i].setTextColor(Color.RED);
name[i].setTextSize(12);
layout.addView(name[i]);
layout.addView(website[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
when i want to get the View I got this error: Only the original thread that created a view hierarchy can touch its views.
anybody have a solution for this code?
PSD: this is a rss parse
You cant update the UI on the a seperate thread. You only can update it on the Main thread
new Thread(new Runnable(){
public void run(){
begin();
pd.dismiss();
}
}).start();
For this you should use an AsnycTask. It has methods that allow you to update the main UI while doing background work, or after or before it is complete.

Can't parse XML with DOM in android

I am having some trouble parsing XML in Android from an URL. I don't know if it's the XML parsing that's the problem or only when I am trying to show it on the screen because
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this, android.R.layout.simple_list_item_1, stopNumbers));
wont show anything. The code below works perfectly in a java program.
URL: http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0
try {
ArrayList<Double> xCords = new ArrayList<Double>();
ArrayList<Double> yCords = new ArrayList<Double>();
ArrayList<String> stopNumbers = new ArrayList<String>();
ArrayList<String> bussLocations = new ArrayList<String>();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder
.parse(new URL(
"http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0")
.openStream());
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfObjects = doc.getElementsByTagName("iGNMObject");
for (int s = 0; s < listOfObjects.getLength(); s++) {
Node firstPersonNode = listOfObjects.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList stopNumList = firstPersonElement
.getElementsByTagName("StopNumber");
Element ageElement = (Element) stopNumList.item(0);
if (ageElement != null) {
NodeList textAgeList = ageElement.getChildNodes();
String stop = ((Node) textAgeList.item(0))
.getNodeValue().trim();
stopNumbers.add(stop);
// ------
// -------
NodeList xPosList = firstPersonElement
.getElementsByTagName("XPosition");
Element firstNameElement = (Element) xPosList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
String temp2 = ((Node) textFNList.item(0))
.getNodeValue().trim();
double x = Double.parseDouble(temp2);
xCords.add(x);
// -------
NodeList yPosList = firstPersonElement
.getElementsByTagName("YPosition");
Element lastNameElement = (Element) yPosList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
String temp3 = ((Node) textLNList.item(0))
.getNodeValue().trim();
double y = Double.parseDouble(temp3);
yCords.add(y);
// ----
NodeList stopAkaList = firstPersonElement
.getElementsByTagName("StopAka");
Element stopAka = (Element) stopAkaList.item(0);
NodeList textStopAKAList = stopAka.getChildNodes();
String plats = ((Node) textStopAKAList.item(0))
.getNodeValue().trim();
bussLocations.add(plats);
} else {
}
}// end of if clause
}// end of for loop with s var
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this,
android.R.layout.simple_list_item_1, stopNumbers));
} catch (Exception e) {
}
}
}
}
Solved it. I had forgot to add internet permission in the manifest.

Categories

Resources