I am using the following code by the Android-people-XMLParsing example for parsing XML file and it is working perfectly fine..
but it retrieve the data in TextView i want to put this data in a ListView..
I tried by creating CustomAdapter and by changing the Activity into the ListActivity..but nothing works..i can see only a blank screen..Can anyone help me to do this...
Thanks!!
package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingExample extends Activity {
/** Create Object For markerList Class */
mymarkers markerList =null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** 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 address[];
TextView city[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("xxxxxxxxx");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
markerList = MyXMLHandler.markerList;
/** Assign textview array lenght by arraylist size */
name = new TextView[markerList.getName().size()];
address = new TextView[markerList.getaddress().size()];
city = new TextView[markerList.getCity().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < markerList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+markerList.getName().get(i));
address[i] = new TextView(this);
address[i].setText("address = "+markerList.getaddress().get(i));
city[i] = new TextView(this);
city[i].setText("city = "+markerList.getCity().get(i));
System.out.println("count33..."+markerList.getCity().size());
city[i].setBackgroundColor(Color.WHITE);
layout.addView(name[i]);
layout.addView(address[i]);
layout.addView(city[i]);
//layout.addView(border[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
I've answered a very similar question few days back that you might want to check. You could check the question Android: Sax parsing to a listview and check the accepted answer. Follow the instruction until getView() part and you should be ok.
In summary here is what you need to do:
Use DOM instead of SAX, it's simpler and perfect for ListView
Implement an Adapter that extends BaseAdapter passing the root element to this adapter
Implement getView in the adapter to add the TextView that you want
Again I've laid out the steps in the Android: Sax parsing to a listview. Let me know if you have any further questions
Related
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());
}
}
}
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.
So i have an activity that imports a list of names from a .txt that is on a webserver.
But how do i set the background color? On the page that shows the names in the app?
Because it doesnt use the layout i set? Which is roster.xml
Do i have to do something to the .txt file?
Roster.class code:
package com.frede.iii;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Window;
import android.widget.ScrollView;
import android.widget.TextView;
public class IIIRoster extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.roster);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Scrollview
ScrollView sv = new ScrollView(this);
/* We will show the data we read in a TextView. */
TextView tv = new TextView(this);
/* Will be filled and displayed later. */
String myString = null;
try {
/* Define the URL we want to load data from. */
//http://androidtest.host.org/roster.txt
URL myURL = new URL(
"http://androidtest.host.org/roster.txt");
/* Open a connection to that URL. */
URLConnection ucon = myURL.openConnection();
/* Define InputStreams to read
* from the URLConnection. */
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/* Read bytes to the Buffer until
* there is nothing more to read(-1). */
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
myString = new String(baf.toByteArray());
} catch (Exception e) {
/* On any Error we want to display it. */
myString = e.getMessage();
}
/* Show the String on the GUI. */
tv.setText(myString);
// Adds textview to scrollview
sv.addView(tv);
// Sets contentview to scrollview
this.setContentView(sv);
}
}
Hello you can simple use tv.setBackgroundColor(COLOR.XYX) or sv.setBackgroundColor(COLOR.XYX)
Also at the same time a textColor can be applied to text as tv.setTextColor(COLOR.XYX)
For defining you own colors to be used at run time, use the following:
1.In the string.xml file use the following tag
<color name="mycolor">#F5DC49</color>
Now in your code.
tv.setTextColor(getResources().getColor(R.color.mycolor))
2.Also we can set RGB values as:
tv.setTextColor(Color.rgb(170, 00, 00));
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.
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.