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.
Related
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);
}
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!
I need to parse document using DOM parser in android. I was unable to print all the node values
My Sample XML is:`
<xml_api_reply version="1">
<news module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<title data="Top Stories"/>
<section_type data="0"/>
<news_entry>
<title data="BSE Sensex breaches 19000, Nifty above 5800"/>
<url data="http://in.reuters.com/article/2012/10/04/sensex-above-19000-on-reform-hopes- idINDEE89301O20121004"/>
<snippet data="| MUMBAI (Reuters) - The Nifty rose above 5800 points on Thursday, joining the Sensex in breaching key psychological levels, after continued government reform measures sparked hopes for continued action. Banks led gainers, with ICICI Bank (ICBK."/>
<source data="Reuters India"/>
<date data="3 hours ago"/>
<num_related data="145"/>
<cluster_url data="http://google.co.in/news/story?ncl=da6VmeBXmuquikM&hl=en"/>
</news_entry>
<news_entry>
<title data="Uncertainty over Kingfisher resuming operations tomorrow"/>
<url data="http://www.hindustantimes.com/India-news/NewDelhi/Uncertainty-over- Kingfisher-resuming-operations-tomorrow/Article1-939628.aspx"/>
<snippet data="Hopes of ailing Kingfisher Airlines resuming operations on Friday has faded with last ditch efforts by the management to persuade striking engineers and pilots to return to work failing to end the deadlock over the issue of non-payment of salaries for ..."/>
<source data="Hindustan Times"/>
<date data="1 hour ago"/>
<num_related data="993"/>
<cluster_url data="http://google.co.in/news/story?ncl=dzf460GzYKTOyxM&hl=en"/>
</news_entry>
</news>
</xml_api_reply>`
and I am using following code to parse the xml
xmlactivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
//static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title ";
static final String KEY_COST = "url ";
static final String KEY_DESC = "snippet";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
//map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
//map.put(KEY_COST, parser.getValue(e, KEY_COST));
//map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
/* ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });*/
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME }, new int[] {
R.id.name});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
//String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//in.putExtra(KEY_NAME, name);
//in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
and xmlParser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
please help me . what is the problem and suggestion
thanks in advance!!!!!!!!!
//Try this code..
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
URLConnection conn = null;
InputStream inputStream = null;
URL urls = new URL(url);
conn = urls.openConnection();
conn.setConnectTimeout(10000);
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(10000);
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringWriter writer=new StringWriter();
String line="";
while ( null!=(line=in.readLine())){
writer.write(line);
}
xml =writer.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(new StringReader(xml)));
doc.normalize();
//InputSource is = new InputSource();
// is.setCharacterStream(new StringReader(xml));
// doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
return child.getTextContent();
}
}
}
}
return "";
}
// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title";
static final String KEY_COST = "url";
static final String KEY_DESC = "snippet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
System.out.println("attrlength"+attributes.getLength());
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
menuItems.add(map);
}
}
I have made changes to my code, as I have given this.setContentView(sv); right at the beginning of onCreate(), but the view is loading only after executing try catch it seems. Is it really possible to show the view before executing try catch?
public class viewstoryActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Create a new layout to display the view */
ScrollView sv = new ScrollView(this);
LinearLayout layout1 = new LinearLayout(this);
layout1.setOrientation(LinearLayout.VERTICAL);
this.setContentView(sv);
/** Create a new textview array to display the results */
try {
LinearLayout layout[];
TextView name[];
ImageView website[];
TextView category[];
URL url = new URL("http://gdata.youtube.com/feeds/api/videos?start-index=1&max-results=25&vq=itsaperfectstory&orderby=relevance");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
NodeList nodeList = doc.getElementsByTagName("entry");
/** Assign textview array lenght by arraylist size */
layout = new LinearLayout[nodeList.getLength()];
name = new TextView[nodeList.getLength()];
website = new ImageView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
layout[i]= new LinearLayout(this);
layout[i].setOrientation(LinearLayout.VERTICAL);
layout[i].setBackgroundResource(R.drawable.allicon_bg);
layout[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,150));
name[i] = new TextView(this);
website[i] = new ImageView(this);
category[i] = new TextView(this);
name[i].setPadding(50, 20,0,0);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText(((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("media:content");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
final String url1 = websiteElement.getAttribute("url");
NodeList websiteList1 = fstElmnt.getElementsByTagName("media:thumbnail");
Element websiteElement1 = (Element) websiteList1.item(1);
String test=websiteElement1.getAttribute("url");
Bitmap bm = null;
URL aURL = new URL(test);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close(); // TODO: handle exception
website[i].setImageBitmap(bm);
website[i].setMaxWidth(50);
website[i].setPadding(380, 0, 0, 0);
layout[i].addView(name[i]);
layout[i].addView(website[i]);
layout1.addView(layout[i]);
layout[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle bundle = new Bundle();
// add data to bundle
bundle.putString("url", url1);
Intent intent=new Intent(viewstoryActivity.this, VidActivity.class);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
overridePendingTransition (R.anim.right_slide_out, R.anim.right_slide_out);
}
});
}
} catch (Exception e) {
System.out.println("XML Parsing Exception = " + e);
}
/** Set the layout view to display */
sv.addView(layout1);
}
}
After analyzing your onCreate(), it is obvious that your Activity would take a while to show. All of your UI is designed and added dynamically and must (according to your code) wait for the data to load and be parsed and organized. In other words, you are blocking your UI with your data processing.
Consider moving your data loading to an AsyncTask. Also consider designing/loading your UI before the data. This would allow your user to see something, even if its not complete. And you can always add Views or change the display properties after the onCreate(). It will also get reduce the perception of the UI lag.
As the others have said move your work into an AsyncTask so that it's not blocking main thread. If you're interested in seeing exactly what's taking all the time then I'd suggest taking some time to read up on TraceView - it's a great tool for profiling.
suggestion move big try block to another thread, don't block the ui.
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.