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!
Related
I want make url in android studio.
When I make multi var, I can see wrong word in emulate.
Below is source code.
content[i] has number and title[i] has text.
"content[1] = 1 content[2] = 2 content[3] = 3..."
"title[1] = test1 title[2] = test2 title[3] = test3..."
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
dist[i] = new TextView(this);
contentid[i] = new TextView(this);
title[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList distList = fstElmnt.getElementsByTagName("dist");
Element distElement = (Element) distList.item(0);
distList = distElement.getChildNodes();
NodeList contentidList = fstElmnt.getElementsByTagName("contentid");
Element contentidElement = (Element) contentidList.item(0);
contentidList = contentidElement.getChildNodes();
contentid[i].setText(((Node) contentidList.item(0)).getNodeValue());
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i].setText("TITLE = "
+ ((Node) titleList.item(0)).getNodeValue() + ((Node) distList.item(0)).getNodeValue());
title[i].setClickable(true);
title[i].setMovementMethod(LinkMovementMethod.getInstance());
String URL_ANSWER = "<a href='http://korean.visitkorea.or.kr/kor/bz15/where/festival/festival.jsp?cid="+ contentid[i] + "'>" + title[i] + "</a>";
title[i].setText(Html.fromHtml(URL_ANSWER));
// addView is best used with setting LayoutParams.
// eg addView(view, layoutParams). The following is for simplicity.
layout.addView(title[i]);
}
You're including your TextView on the url, try like this:
String URL_ANSWER = "" +"";
I want to parse "ALışVERIş" type of content from service.
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
What I tried DOM Parser instead of XaxParser. Check below function and call it inside background thread :
public String readXML(){
StringBuilder stringBuilder = new StringBuilder();
try {
URL _url = new URL("http://182.160.161.2/~siva/turkish/web_serv/category.php?order_by=desc&category_id=2");
File fXmlFile = new File(new InputSource(_url.openStream()).getByteStream().toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(_url.openStream()).getByteStream());
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("document");
Node nResp = nList.item(0);
Element fstElmnt = (Element) nResp;
NodeList nameList1 = fstElmnt.getElementsByTagName("response");
Node mCat = nameList1.item(0);
Element catElmt = (Element) mCat;
NodeList catList = catElmt.getElementsByTagName("category");
System.out.println("----------------------------");
for (int temp = 0; temp < catList.getLength(); temp++) {
Node nNode = catList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
stringBuilder.append("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent()+"\n");
stringBuilder.append("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
System.out.println("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent());
System.out.println("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Here is a screenshot of my device, Have a look :
You can see those turkish language too :)
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.
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.