pass xml file from local storage - java

i want to pass a xml file from my internal storage
with my Activity:
my error:
07-06 01:58:39.494: E/Error:(15253): Unexpected token (position:TEXT /sdcard/xml.xlm...#1:24 in java.io.StringReader#4152db98)
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParserLocal parser = new XMLParserLocal();
//String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement("storage/emulated/0/xml.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_COST2, parser.getValue(e, KEY_COST2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
// 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_ID, KEY_COST, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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 deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).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);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
and here my XMLParserLocal:
package de.heron.cloudbox;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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 org.xml.sax.SAXException;
import android.util.Log;
public class XMLParserLocal {
// constructor
public XMLParserLocal() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = "/xml.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));
}
}
can someone help me with my probelm?
edit:
here my xml there i want to pass with my Activity, i have take empty on parts of xml there was other words:
<?xml version="1.0" encoding="utf-8"?>
<devices>
<device>
<deviceid>empty</deviceid>
<devicename>empty</devicename>
<actions>empty</actions>
<actions2>empty</actions2>
<devicetype>empty</devicetype>
<texton>empty</texton>
<textoff>empty</textoff>
</device>
<device>
<deviceid>empty</deviceid>
<devicename>empty</devicename>
<actions>empty</actions>
<actions2>empty</actions2>
<devicetype>empty</devicetype>
<texton>empty</texton>
<textoff>empty</textoff>
</device>
</devices>

The XML you posted above isn't valid. You have
</device>
<device>
<device>
which has two open device tags in a row. Then you open another right before you end the xml section
<device>
</devices>

Related

Android Xml data parsing

I am trying to parse XML and display it into list view but after running the app nothing happen the list display but not with XML data. I don't know if I missing something please can help me.
MainActivity class
public class MainActivity extends ListActivity {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ListView myList=(ListView)findViewById(android.R.id.list);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = null; // getting XML
try {
xml = parser.getXmlFormUrl(URL);
} catch (IOException e) {
e.printStackTrace();
}
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, "Rs." + 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.activity_main,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
}
}
XmlParser class
public class XMLParser {
String result;
public String getXmlFormUrl(String link) throws IOException{
URL url=new URL(link.toString());
HttpURLConnection UrlConnection= (HttpURLConnection) url.openConnection();
int status=UrlConnection.getResponseCode();
if(status==200){
InputStream inputStream=UrlConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF8"));
StringBuilder stringBuilder= new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append((line+"\n"));
}
result=stringBuilder.toString();
inputStream.close();
}
return result;
}
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 DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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 "";
}
}
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="android.prgguru.com.xmlparsingg.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="73dp" />
</RelativeLayout>
after this line I think the list should display with XML data but nothing happens
myList.setAdapter(adapter);
ids.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="desciption" type="id" />
<item name="cost" type="id" />
<item name="name" type="id" />
<item name="List" type="id"/>
</resources>
create main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
creare list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#dc6800"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
<TextView
android:id="#+id/desciption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:paddingBottom="2dip">
</TextView>
<!-- Linear layout for cost and price Cost: Rs.100 -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Cost Label -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:gravity="left"
android:textStyle="bold"
android:text="Cost: " >
</TextView>
<!-- Price Label -->
<TextView
android:id="#+id/cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:textStyle="bold"
android:gravity="left">
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
create MainActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#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, "Rs." + 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 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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);
}
});
}
}
create XMLParser.java
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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 org.xml.sax.SAXException;
import android.util.Log;
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));
}
}
all the code copied from here you just need to copy paste the above code and then let me know if it is working or not

how to get data from rss?

I can't get data from rss...null exception
I retrieve from this link, it only has
<?xml version="1.0" encoding="utf-8"?>
<GoldQuotes>
<Price Date="2013-11-28 09:22" Value="1244.30" />
<Price Date="2013-11-28 09:20" Value="1243.10"/>
<Price Date="2013-11-28 09:18" Value="1243.30"/>
[...]
</GoldQuotes>
this is my java fragment code
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("GoldQuotes"); //***
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
dissectNode(nl, i);
}
}//if
[...]
public void dissectNode(NodeList nl, int i) {
try {
Element entry = (Element) nl.item(i);
Element price = (Element) entry.getElementsByTagName("Price").item(0);
String priceValue = price.getAttribute("Value"); //get gold value
SingleNewsItem singleItem = new SingleNewsItem(priceValue);
newsList.add(singleItem);
} catch (DOMException e) {
e.printStackTrace();
}
}// dissectNode
After I do NodeList nl = docEle.getElementsByTagName("GoldQuotes"). I test with nl.getLength() which returns 0..
Am I missing anything?
The document you are trying to parse is not rss, just a custom xml format. After you parse it, it's enough to modify our code like this:
// this returns the root element, ie "GoldQuotes"
Element docEle = dom.getDocumentElement();
// get the list of Price elements children of the root
NodeList nl = docEle.getElementsByTagName("Price");
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
// get the i-th Price element from the nodelist
Element entry = (Element) nl.item(i);
// get its Value attribute
String priceValue = entry.getAttribute("Value");
[....]
}
}
Try this..
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
String url = "https://www.igolder.com/GoldData.ashx?type=Historical&hours=24&currency=USD&tz=UTC&unit=oz&output=xml";
ProgressDialog pDialog;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(url).executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR, new String[] { null });
else
new XmlParsing(url).execute(new String[] { null });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String urls;
// constructor
public XmlParsing(String urls) {
this.urls = urls;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(NetActivity.this,
"Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(urls);
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("GoldQuotes");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("Price");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
String priceValue = nameElement.getAttribute("Value"); //get gold value
SingleNewsItem singleItem = new SingleNewsItem(priceValue);
newsList.add(singleItem);
System.out.println("Value : "
+ (nameElement.getAttribute("Value")));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}

Android : how to read XML data in URL

I want to read XML data from URL and have tried in different ways. But unable to find the answer. Iam developing a agumented reality application, where iam reading location information from XML ( which is in URL )
Iam new bee to android as well
I have the following XML data.
<specialoffers>
<categories>
<category>
<![CDATA[ 0% Installment Payment Plan Offers ]]>
</category>
<merchants>
<merchantname>
<![CDATA[ EmaxIPP ]]>
</merchantname>
<merchantbigimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg
]]>
</merchantbigimage>
<merchantsmallimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
]]>
</merchantsmallimage>
<merchantmobileimage>
<![CDATA[ http://www.XXX.com ]]>
</merchantmobileimage>
<mobilehighlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on
all purchases made </b>
]]>
</mobilehighlight>
<highlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on all purchases
made with your </b>
]]>
</highlight>
<locations>
<location>
<emirate>
<![CDATA[ XXX]]>
</emirate>
<address>
<![CDATA[ Center 1 ]]>
</address>
<latitude>
<![CDATA[ 51.169601 ]]>
</latitude>
<longitude>
<![CDATA[ 61.240395 ]]>
</longitude>
</location>
</merchants>
</categories>
</specialoffers>
Here is the code....
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.adcb.com/specialoffers-test.xml";
// XML node keys
static final String KEY_ITEM = "categories"; // parent node
static final String KEY_ID = "category";
#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));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_ID, "KEY_DESC", "100" }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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_ID, name);
in.putExtra("100", cost);
in.putExtra("KEY_DESC", description);
startActivity(in);
}
});
}
}
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));
}
}
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "category";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_ID);
String cost = in.getStringExtra(KEY_COST);
String description = in.getStringExtra(KEY_DESC);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
You can use xmlpullparser like this :
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
I found a link demonstrating the same example as per your need.Please go through this link
Or just go the android way . A developer guide link
Hope it helps you.
Use SimpleXml xml parsing API for android it'll make your coding easy.

Android - get XML from web

I'm trying to get XML datas from web and to show these datas into ListView. But something's going wrong when i run the project. Can you help me for this problem,please? Thank you.
XMLParser.java
public class XMLParser extends Activity {
public String getXmlFromUrl(String url) {
String xml = null;
try {
new Thread(new Runnable() {
public void run() {
try {
URL uri=new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
System.out.println("done");
}
catch(Exception e) {
e.printStackTrace();
}
}
}).start();
//readfilethread.start();
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("here");
// HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
//xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
// return XML
return xml;
}
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 DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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 "";
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables..
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// -> menuItems
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, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// 2. 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.description, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
android.widget.ListView lv = getListView();
// listening to single list item click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
'
LOGCAT PART
08-25 08:34:10.211: E/AndroidRuntime(1700): FATAL EXCEPTION: main
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Looper.loop(Looper.java:137)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.main(ActivityThread.java:5039)
....
08-25 08:34:10.341: I/System.out(1700): done
Try this codes ...
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class NetActivity extends Activity {
String url = "http://api.androidhive.info/pizza/?format=xml";
// Progress dialog
ProgressDialog pDialog;
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> id;
ArrayList<String> cost;
ItemAdapter adapter1;
ListView list;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_net);
list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
id = new ArrayList<String>();
cost = new ArrayList<String>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(url).execute(new String[]{null});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String urls;
// constructor
public XmlParsing(String urls) {
this.urls = urls;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(urls);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
System.out.println("name : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("id");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
description.add(""+ ((Node) nameList1.item(0)).getNodeValue());
System.out.println("id : "+ ((Node) nameList1.item(0)).getNodeValue());
Element fstElmnt2 = (Element) node;
NodeList nameList2 = fstElmnt2.getElementsByTagName("cost");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
id.add(""+ ((Node) nameList2.item(0)).getNodeValue());
System.out.println("cost : "+ ((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) node;
NodeList nameList3 = fstElmnt3.getElementsByTagName("description");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
cost.add(""+ ((Node) nameList3.item(0)).getNodeValue());
System.out.println("description : "+ ((Node) nameList3.item(0)).getNodeValue());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView id_text;
public TextView cost_text;
}
public ItemAdapter(XmlParsing xmlParsing) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.id_text = (TextView) view.findViewById(R.id.id_text);
holder.cost_text = (TextView) view.findViewById(R.id.cost_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+description.get(position));
holder.id_text.setText(""+id.get(position));
holder.cost_text.setText(""+cost.get(position));
return view;
}
}
}

parsing xml asynctask and writing in listview

i want to parse my xml in asynctask because it won´t work without asynctask on android 4.0 +.The problem is that i cant write my strings in listview on my asynctask.
Here is my xml parsing activity:
package de.heron.cloudbox;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
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 org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidXMLParsingActivity extends ListActivity{
String dwnload_file_path = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
String dest_file_path = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
Button b1;
ProgressDialog dialog = null;
///storage/emulated/0/everhomeapp.xml
// All static variables
static final String URL = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
//file:///storage/emulated/0/everhomeapp.xml
// XML node keys
static final String KEY_ITEM = "device"; // parent node
static final String KEY_ID = "deviceid";
static final String KEY_NAME = "devicename";
static final String KEY_actionid = "actions";
static final String KEY_actionid2 = "actions2";
static final String KEY_DESC = "devicetype";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
ArrayList<String> mImageLink;
String[] actions = new String[] {
"Alle Räume",
"Wohnzimmer",
"Küche",
"Gäste-Wc"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
overridePendingTransition( R.anim.leftright, R.anim.rightleft );
setTitle("Geräte");
getActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
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);
// 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_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
// Adding menuItems to ListView
ListAdapter adapter2 = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter2);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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 cost2 = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_actionid, cost);
in.putExtra(KEY_actionid2, cost2);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
try {
URL url = new URL("http://h.t-softec.de/heron.website.app/android/everhomeapp.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"everhomeapp.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
parseFile();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
parseFile();
} catch (IOException e) {
e.printStackTrace();
parseFile();
}
}
public void parseFile(){
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
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);
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_actionid, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
}
public void parsexmllocal(){
mImageLink = new ArrayList<String>();
try{
File file = new File("mnt/sdcard/kursywalut.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("image");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
mImageLink.add(fstElmnt.getAttribute("link"));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
public void clicksound(View view){
MediaPlayer mp = MediaPlayer.create(this, R.raw.clicksound);
mp.start();
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.refresh:
try {
URL url = new URL("http://h.t-softec.de/heron.website.app/android/everhomeapp.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"everhomeapp.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
Toast.makeText(this, "Geräteliste erfolgreich aktualisiert!", Toast.LENGTH_LONG).show();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Handler handler4 = new Handler();
handler4.postDelayed(new Runnable()
{
#Override
public void run()
{
parseFile();
}
}, 100);
break;
case R.id.change:
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
break;
case android.R.id.home:
Intent i2 = new Intent(this, AndroidXMLParsingActivity2.class);
startActivity(i2);
break;
}
return true;
}
}
and here is my singlemenuitemactivity:
package de.heron.cloudbox;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
EditText txtCode;
// XML node keys
static final String KEY_NAME = "name";
static final String KEY_actionid = "cost";
static final String KEY_actionid2 = "cost2";
static final String KEY_DESC = "description";
static final String KEY_ID = "deviceid";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cost = in.getStringExtra(KEY_actionid);
String cost2 = in.getStringExtra(KEY_actionid2);
String description = in.getStringExtra(KEY_DESC);
String deviceid = in.getStringExtra(KEY_ID);
String on = in.getStringExtra(KEY_texton);
String off = in.getStringExtra(KEY_textoff);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
TextView lblid = (TextView) findViewById(R.id.id_label);
// TextView lblon = (Button) findViewById(R.id.on);
// TextView lbloff = (Button) findViewById(R.id.off);
Button lblon = (Button)findViewById(R.id.on);
lblon.getText().toString();
lblon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
txtCode.setText(settings.getString("Code", "").toString());
String[] url={"http://everhome.de/api/applive/", (settings.getString("Code", "")), "/" + KEY_ID,"/" + KEY_actionid};
new onoff(SingleMenuItemActivity.this).execute(url);
}});
Button lbloff = (Button)findViewById(R.id.off);
lbloff.getText().toString();
lbloff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] url={"http://everhome.de/api/applive/", "8ef43502ad3dc04f87b4a48b993878c0","/" + KEY_ID,"/" + KEY_actionid2};
new onoff(SingleMenuItemActivity.this).execute(url);
}
});
lblName.setText(name);
lblCost.setText(cost);
lblCost.setText(cost2);
lblDesc.setText(description);
lblid.setText(deviceid);
lblon.setText(on);
lbloff.setText(off);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setIcon(R.drawable.ic_launcher);
setTitle("Geräte");
Button devices = (Button) findViewById(R.id.devices);
devices.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(SingleMenuItemActivity.this, AndroidXMLParsingActivity.class);
startActivity(i);
}
});
Button scenes = (Button) findViewById(R.id.scenes);
scenes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(SingleMenuItemActivity.this, AndroidXMLParsingActivity2.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.refresh:
break;
}
return true;
}
}
i hope anybody can help me to resolve my problem.
Update:
thats was the test with asynctask:
class xmlparse extends AsyncTask<Void, Void, Void> {
static final String KEY_ITEM = "device"; // parent node
static final String KEY_ID = "deviceid";
static final String KEY_NAME = "devicename";
static final String KEY_actionid = "actions";
static final String KEY_actionid2 = "actions2";
static final String KEY_DESC = "devicetype";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
#Override
protected Void doInBackground(Void... params) {
/*
make connection & download XML here,
use your XML parser class object to parse the xml from here
create ArrayList & etc. from here...
*/
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//
//File xml = parser.getXmlFromUrl(URL); // getting XML
//Document doc = parser.getDomElement(xml); // getting DOM element
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
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_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
// adding HashList to ArrayList
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// postexecute logic
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// pre execute logic
super.onPreExecute();
}
}
but the problem is that i want to put the strings(menu items ) in listview with the listadapter:
ListAdapter adapter2 = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter2);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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 cost2 = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
and i dont know how i can make this when the parser runs in asynctask.
that make the parser to put the menuitems to the listadapter:
menuItems.add(map);
Reference your adapter through a WeakReference when initializing your Asynctask.
Parametrize the AsyncTask to return whatever you need to return, e.g. a List<String>. The connection and data pulling happens in doInBackground.
In onPostExecute, check your WeakReference.get is not null and populate the adapter.
You can use the droidQuery library to asynchronously download an XML Document given a URL. For example:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("GET")
.context(this)
.dataType("xml")
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
Document xml = (Document) params[0];
//TODO parse xml here. This is the UI Thread, so you can also modify your TextViews here.
}
})
.error(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
AjaxError e = (AjaxError) params[0];
droidQuery.alert("Error: " + e.status + ": " + e.error);
}
}));

Categories