I have a question here, how can i find the direction of a particular point from fixed point. For example, from my current location in Google Maps, I want to know the direction of a particular point. How can i achieve this. Can any one guide me regarding to this. Thanks in advance..
Try this code::
//calling method from onCreate() method
String pairs[] = getDirectionData(sourceLat,sourceLong, destinationLat, destinationLong );
private String[] getDirectionData(String sourceLat, String sourceLong,
String destinationLat, String destinationLong) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&" + "saddr="
+ sourceLat + "," + sourceLong + "&daddr=" + destinationLat
+ "," + destinationLong + "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
Related
We are creating an Android application and we need to calculate exact road distance between two fixed points. We require road distance not the Arial distance(Bird flying distance). We need to calculate the estimate trip cost before the trip starts.
Thanks in Advance.
All the answers and helps will be appreciated.
use goolge api
public float getDistance(double lat1, double lon1, double lat2, double lon2) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = {"text"};
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms =String.valueOf( args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
Float f=Float.valueOf(result_in_kms);
return f*1000;
}
Here is a variation of the first answer. First call getDocument with start and end location, mode (driving, transit, cycling, walking), language. Then pass that document to getTurnByTurn(). This will return an array of 'steps' or legs of a trip, with a distance between the previous step's end point and the new step's end point. Might be in kilometers, need to convert to miles if necessary.
public Document getDocument(String start, String dest, String mode, String language) {
try {
start = URLEncoder.encode(start, "utf-8");
dest = URLEncoder.encode(dest, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
long milliseconds = System.currentTimeMillis();
long seconds = milliseconds/1000;
String url = "https://maps.googleapis.com/maps/api/directions/xml?departure_time="
+ seconds
+ "&origin=" + start
+ "&destination=" + dest
+ "&language=" + language
+ "&sensor=false&mode=" + mode;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public ArrayList<SearchItem> getTurnByTurn (Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<SearchItem> listDirections = new ArrayList<SearchItem>();
nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();
Node distanceNode = nl2.item(getNodeIndex(nl2, "distance"));
nl3 = distanceNode.getChildNodes();
Node textNode = nl3.item(getNodeIndex(nl3, "text"));
String distance = textNode.getTextContent();
Node durationNode = nl2.item(getNodeIndex(nl2, "duration"));
nl3 = durationNode.getChildNodes();
textNode = nl3.item(getNodeIndex(nl3, "text"));
String duration = textNode.getTextContent();
Node instructionsNode = nl2.item(getNodeIndex(nl2, "html_instructions"));
String instructions = instructionsNode.getTextContent();
String details = distance + " -- " + duration;
listDirections.add(new SearchItem(instructions, details, "", false));
}
}
return listDirections;
}
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 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 am working on an android app in which i have to fetch data from a RSS feed, i am able to read Title, link and facing problem with description. if it is in this format
<description>
worsening of developments in......
</description>
i am able to read it , but in some rss feeds having this format also
<description>
<p><a href="http://news.yahoo.com/ap-sources
</description>
i am not getting this text..
this is the Rss feed url : http://news.yahoo.com/rss/politics.
how to read this description..
package com.samir.XMLParser;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class HTMLRemoverParser {
HTMLRemoverBean objBean;
Vector<HTMLRemoverBean> vectParse;
int mediaThumbnailCount;
boolean urlflag;
int count = 0;
public HTMLRemoverParser() {
try {
vectParse = new Vector<HTMLRemoverBean>();
URL url = new URL("http://news.yahoo.com/rss/politics");
URLConnection con = url.openConnection();
System.out.println("Connection is : " + con);
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
System.out.println("Reader :" + reader);
String inputLine;
String fullStr = "";
while ((inputLine = reader.readLine()) != null)
fullStr = fullStr.concat(inputLine + "\n");
InputStream istream = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(istream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("item");
System.out.println();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
objBean = new HTMLRemoverBean();
vectParse.add(objBean);
objBean.title = getTagValue("title", eElement);
objBean.description = getTagValue("description", eElement);
String noHTMLString = objBean.description.replaceAll("\\<.*?\\>", "");
objBean.description=noHTMLString;
objBean.link = getTagValue("link", eElement);
objBean.pubdate = getTagValue("pubDate", eElement);
}
}
for (int index1 = 0; index1 < vectParse.size(); index1++) {
HTMLRemoverBean ObjNB = (HTMLRemoverBean) vectParse
.get(index1);
System.out.println("Item No : " + index1);
System.out.println();
System.out.println("Title is : " + ObjNB.title);
System.out.println("Description is : " + ObjNB.description);
System.out.println("Link is : " + ObjNB.link);
System.out.println("Pubdate is : " + ObjNB.pubdate);
System.out.println();
System.out
.println("-------------------------------------------------------------------------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
public static void main(String[] args) {
new HTMLRemoverParser();
}
}
And Bean is ::
package com.samir.XMLParser;
public class HTMLRemoverBean {
public String title;
public String description;
public String link;
public String pubdate;
}
When you detect that the block of text is HTML, open it in a WebView instead of a TextView. My solution looks like this:
WebView wv = (WebView) v.findViewById(R.id.feed_entry_detail);
wv.loadData(mContentFromFeed, "text/html; charset=utf-8", null);
Am having you-tube links like http://www.youtube.com/v/YR71GnQ4CU4?f=videos&app=youtube_gdata , then how to convert it to RTSP format to play in VideoView.
Am searching gdata api with this: http://gdata.youtube.com/feeds/api/videos?&max-results=20&v=2&format=1&q="+ URLEncoder.encode(activity.criteria) but i cant find how to get related RTSP url.
I got my answer ..thanx to this
Element rsp = (Element)entry.getElementsByTagName("media:content").item(1);
String anotherurl=rsp.getAttribute("url");
In gdata api only we are getting this type of links : rtsp://v3.cache7.c.youtube.com/CiILENy73wIaGQlOCTh0GvUeYRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
These are playing in VideoView.
This might be a little late. Here is some working code for people having trouble.
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
doc.getDocumentElement ().normalize ();
NodeList content = doc.getElementsByTagName("media:content");
for(int i=0; i<content.getLength(); i++){
Element rsp = (Element)content.item(i);
result.add(rsp.getAttribute("url"));
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
Below is the function which can get you RTSP link for the youtube video
public static String getUrlVideoRTSP(String urlYoutube) {
try {
String gdy = "http://gdata.youtube.com/feeds/api/videos/";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String id = extractYoutubeId(urlYoutube);
URL url = new URL(gdy + id);
Log.i(MyActivity.class.getSimpleName(), url.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Document doc = documentBuilder.parse(connection.getInputStream());
Element el = doc.getDocumentElement();
NodeList list = el.getElementsByTagName("media:content");///media:content
String cursor = urlYoutube;
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node != null) {
NamedNodeMap nodeMap = node.getAttributes();
HashMap<String, String> maps = new HashMap<String, String>();
for (int j = 0; j < nodeMap.getLength(); j++) {
Attr att = (Attr) nodeMap.item(j);
maps.put(att.getName(), att.getValue());
}
if (maps.containsKey("yt:format")) {
String f = maps.get("yt:format");
if (maps.containsKey("url")) {
cursor = maps.get("url");
}
if (f.equals("1"))
return cursor;
}
}
}
return cursor;
} catch (Exception ex) {
Log.e("Get Url Video RTSP Exception======>>", ex.toString());
}
return urlYoutube;
}
private static String extractYoutubeId(String url) throws MalformedURLException {
String id = null;
try {
String query = new URL(url).getQuery();
if (query != null) {
String[] param = query.split("&");
for (String row : param) {
String[] param1 = row.split("=");
if (param1[0].equals("v")) {
id = param1[1];
}
}
} else {
if (url.contains("embed")) {
id = url.substring(url.lastIndexOf("/") + 1);
}
}
} catch (Exception ex) {
Log.e("Exception", ex.toString());
}
return id;
}