how to get inner content of xml in android? - android

how to get inner content of xml in android?
For example if the
I have used following code but it does not return actual result..
String xml ="<hello><hai>welcome<hai></hello>";
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(is);
String response = document.getElementsByTagName("hello");
I need the result "<hai>welcome<hai>"..Thanks in advance

i had the same problem and i did this:
i made 2 functions, getxml() checks if there are child nodes
and xmltagswtf() returns the rest of code
public String getxml(Node b){
String va = "";
if (b.hasChildNodes()==true){
int nodes = 0;
int a=b.getChildNodes().getLength();
while (nodes <a){
Node c = b.getChildNodes().item(nodes);
if(c.getNodeName()!="#text"){
va+="<"+c.getNodeName()+">"+getxml(c)+"</"+c.getNodeName()+">";
}else{
va+=getxml(c);
}nodes+=1;
}
}else{va=b.getTextContent();}
return va;
}
public String xmltagswtf(String xmlt, String what) throws SAXException, IOException, ParserConfigurationException{
InputStream is = new ByteArrayInputStream(xmlt.getBytes("UTF-8"));
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(is);
NodeList response = document.getElementsByTagName(what);
Node nod = response.item(0);
String nodos = "";
if (nod.hasChildNodes()==true){
int nodes = 0;
int a=nod.getChildNodes().getLength();
while (nodes <a){
Node c = nod.getChildNodes().item(nodes);
nodos+="<"+c.getNodeName()+">"+getxml(c)+"</"+c.getNodeName()+">";
nodes+=1;
}
}else{
nodos+=nod.getTextContent();
System.out.println(nodos);
}
return nodos;
}
then do something like this:
String xml ="<hello><hai>welcome</hai></hello>";
String hai =xmltagswtf(xml, "hello");

Related

How to scroll webview in Google Glass

I have an Rss feed app displaying title and description from xml. I'm parsing the xml and displaying the content inside webview. When i navigate to webview, i can't able to scroll the content. It's like static. Is there is way to scroll content inside webview?
webview:
title = (TextView) findViewById(R.id.title);
desc = (WebView) findViewById(R.id.desc);
// set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.getPluginState();
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);
ws.setBuiltInZoomControls(true);
// Set the views
title.setText(feed.getItem(pos).getTitle());
desc.loadDataWithBaseURL("http://www.googleglass.gs/", feed
.getItem(pos).getDescription(), "text/html", "UTF-8", null);
Parsing:
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 1; j < clength; j = j + 2) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("content:encoded".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
You have to implement your own WebView and implement that functionality or you can use Native Google Glass WebBrowser with an Intent.
EDIT: You also can try to use native webBrowser with an intent:
Intent intent = new Intent(Intent.ACTION_VIEW);
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent.setClassName("com.google.glass.browser", "com.google.glass.browser.WebBrowserActivity");
intent.setDataAndType(Uri.fromFile(file),mimetype);
startActivity(intent);
You create a HTML file with the content of your XML, you save it in the sdcard and then you open it with Intent.

XML Pullparser: Getting The Value of a Particular node

Lets say I have a XML file:
<catalog>
<book>
<isbn>1</isbn>
<author> A</author>
<title>Title A</title>
<description> Desc A</description>
</book>
<book>
<isbn>2</isbn>
<author>B</author>
<title>Title B</title>
<description>Desc B</description>
</book>
...
<catalog>
As per Android's documentation I can fetch all the data in my Activity like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
stringXmlContent = getEventsFromAnXML(this);
...
}
private String getEventsFromAnXML(Activity activity)
throws XmlPullParserException, IOException {
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.myxmlfile );
xpp.next();
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
stringBuffer.append("\nSTART_TAG: " + xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
stringBuffer.append("\nEND_TAG: " + xpp.getName());
} else if (eventType == XmlPullParser.TEXT) {
stringBuffer.append("\nTEXT: " + xpp.getText());
}
eventType = xpp.next();
}
return stringBuffer.toString();
}
While this fetches all content from XML file, I am really struggling to filter it out for a certain condition.
For example let us say I want to get the author name for book with isbn of 2. How do I filter this data out using pullparser ?
check this out and modify according to your needs
URL url2 = new URL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" +artist+ "&api_key=1732077d6772048ccc671c754061cb18");
URLConnection connection = url2.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(30000);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
final Document document = db.parse(connection.getInputStream());
document.getDocumentElement().normalize();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xPathEvaluator = xPathfactory.newXPath();
XPathExpression nameExpr = xPathEvaluator.compile("//lfm/artist/image");
// XPathExpression nameExpr = xPathEvaluator.compile("//lfm/tracks/track/image");
NodeList nl = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);
for (int zzz = 0; zzz < nl.getLength(); zzz++)
{
Node currentItem = nl.item(zzz);
key = currentItem.getTextContent();
// key = currentItem.getAttributes().getNamedItem("uri").getNodeValue();
}
in the variable key,i get the value of the node which contains image
It requires a bit of guess and check (at least that's what I needed when I did it), but you can easily test a certain node's text to see if the ISBN is 2 (and, if it is, you can continue to parse the data. Otherwise, you can keep going until you get to the next ISBN node.

Getting content of a XML node by the attribute

I have a XML file like this:
<?xml version="1.0"?>
<settings>
<mail id="sender">
<host>content here</host>
<port>25</port>
<account>tmt#example.com</account>
<password>password</password>
</mail>
<mail id="receiver">
<account>tmt#example.com</account>
</mail>
<mail id="support">
<account>tmt#example.com</account>
</mail>
</settings>
How can I get the attribute of each element, parse the content of each element and save the content in SharedPreference
This is what I've done so far:
The Contructor:
public ReadConfig(Context context, ProgressBar progressBar) throws ParserConfigurationException, SAXException, IOException {
this.context = context;
this.progressBar = progressBar;
folders = new CreateApplicationFolder();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new File(folders.getPathToNode() + "/settings_config.xml"));
doc.getDocumentElement().normalize();
}
And my doInBackground method
#Override
protected String doInBackground(String... params) {
Log.i("ROOT NODE: ", doc.getDocumentElement().getNodeName());
NodeList listOfMail = doc.getElementsByTagName("mail");
int totalMail = listOfMail.getLength();
Log.i("LENGTH: ", Integer.toString(totalMail));
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
}
}
From the LogCat I know that there are three elements, which is correct.
import org.w3c.dom.Element;
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
Element e = (Element) firstMailSetting ;
String acc = getTagValue("account", e); <-----
}
private String getTagValue(String sTag, Element eElement) {
try {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
catch (Exception e) {
return "";
}
}

XML Parsing Error

I am consuming a web service as its output is an XML string. I am parsing it into a document and getting each child node value one by one and inserting into my SQLlite table as shown below:
public void DownloadAndInsertProblemAndReasonCode(String serverIPAddress,
String deviceId) {
String SOAP_ACTION = "http://VisionEPODWebService/GetProblemAndReasonCodesNew";
String OPERATION_NAME = "GetProblemAndReasonCodesNew";
String WSDL_TARGET_NAMESPACE = "http://VisionEPODWebService/";
String SOAP_ADDRESS = "";
SOAP_ADDRESS = "http://" + serverIPAddress
+ "/VisionEPODWebService/SystemData.asmx";
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
request.addProperty("deviceID", deviceId);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
DocumentBuilderFactory docBuilberFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilberFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource
.setCharacterStream(new StringReader(response.toString()));
Document doc = docBuilder.parse(inputSource);
NodeList nodesProblemCode = doc
.getElementsByTagName("tblProblemCode");
ContentValues initialProblemCodeValues = new ContentValues();
dbAdapter = new DatabaseAdapter(this.context);
dbAdapter.open();
dbAdapter.BeginTransaction();
dbAdapter.DeleteRecord("tblProblemCode", "", "");
for (int i = 0; i < nodesProblemCode.getLength(); i++) {
Element element = (Element) nodesProblemCode.item(i);
NodeList PKProblemCode = element
.getElementsByTagName("PKProblemCode");
Element line = (Element) PKProblemCode.item(0);
initialProblemCodeValues.put("PKProblemCode",
getCharacterDataFromElement(line).toString());
NodeList ProblemCode = element
.getElementsByTagName("ProblemCode");
line = (Element) ProblemCode.item(0);
initialProblemCodeValues.put("ProblemCode",
getCharacterDataFromElement(line));
NodeList ProblemCodeDescription = element
.getElementsByTagName("ProblemCodeDescription");
line = (Element) ProblemCodeDescription.item(0);
initialProblemCodeValues.put("ProblemCodeDescription",
getCharacterDataFromElement(line).toString());
NodeList VWReturn = element.getElementsByTagName("VWReturn");
line = (Element) VWReturn.item(0);
initialProblemCodeValues.put("VWReturn",
getCharacterDataFromElement(line).toString());
dbAdapter.InsertRecord("tblProblemCode", "",
initialProblemCodeValues);
}
NodeList nodesReasonCode = doc
.getElementsByTagName("tblReasonCode");
ContentValues initialReasonCodeValues = new ContentValues();
dbAdapter.DeleteRecord("tblReasonCode", "", "");
for (int i = 0; i < nodesReasonCode.getLength(); i++) {
Element element = (Element) nodesReasonCode.item(i);
NodeList PKReasonCode = element
.getElementsByTagName("PKReasonCode");
Element line = (Element) PKReasonCode.item(0);
initialReasonCodeValues.put("PKReasonCode",
getCharacterDataFromElement(line).toString());
NodeList ReasonDescription = element
.getElementsByTagName("ReasonDescription");
line = (Element) ReasonDescription.item(0);
initialReasonCodeValues.put("ReasonDescription",
getCharacterDataFromElement(line));
dbAdapter.InsertRecord("tblReasonCode", "",
initialReasonCodeValues);
}
dbAdapter.SetSucessfulTransaction();
dbAdapter.EndTransaction();
dbAdapter.close();
}
catch (Exception exception) {
exception.toString();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
The problem is that after some time the XML string will not have some of child node. For example
"ProblemCode" child node.....at that time the code shows error.
How can I check whether there exists an element in the document, or whether values exist or not for the element?
I think you need to check if the child node exists: specifically for your problem node:
NodeList NL = element.getElementsByTagName("PKProblemCode");
if ((NL==null)||(NL.getLength()==0)) {
//No such node so use a default instead
} else
Element line = (Element) PKProblemCode.item(0);

How to get RTSP Links Android

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;
}

Categories

Resources