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¤cy=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();
}
}
}
Related
I am following this tutorial (http://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/)and try to implement rss feed reader
It working properly when I use
String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
instead of using
String RSSFEEDURL = "http://www.livescience.com/home/feed/health.xml";
This is my splash activity
package com.healthyhub.nadeesha.rsssave;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import com.healthyhub.nadeesha.rsssave.parser.DOMParser;
import com.healthyhub.nadeesha.rsssave.parser.RSSFeed;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SplashActivity extends Activity {
String RSSFEEDURL = "http://www.livescience.com/home/feed/health.xml";
// String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
RSSFeed feed;
String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}
Here is my DOMParser.java
package com.healthyhub.nadeesha.rsssave.parser;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// _feed.clearList();
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory 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 = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
/*newly added*/
/*here it returns NullPointer exception for theString*/
System.out.println( nchild.item(j).getFirstChild().getNodeValue());
/*end*/
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 ("description".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) {
e.printStackTrace();
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
Below part of the above code gives null pointer exception
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
/*newly added*/
/*here it returns NullPointer exception for theString*/
System.out.println( nchild.item(j).getFirstChild().getNodeValue());
/*end*/
This is my DetailFragment.java
package com.healthyhub.nadeesha.rsssave;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.healthyhub.nadeesha.rsssave.parser.RSSFeed;
public class DetailFragment extends Fragment {
private int fPos;
RSSFeed fFeed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fFeed = (RSSFeed) getArguments().getSerializable("feed");
fPos = getArguments().getInt("pos");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.detail_fragment, container, false);
// Initializr views
TextView title = (TextView) view.findViewById(R.id.title);
WebView desc = (WebView) view.findViewById(R.id.desc);
// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);
// Set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setLightTouchEnabled(false);
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);
// Set the views
title.setText(fFeed.getItem(fPos).getTitle());
desc.loadDataWithBaseURL("http://www.livescience.com/health/", fFeed
.getItem(fPos).getDescription(), "text/html", "UTF-8", null);
return view;
}
}
Simply what the above code does is
DOM Parser to Parse the XML data.
method returns the feed(RSSFeed) object:
Splash Activity we now call the method parseXml(String xml) from the DOMParser class
feed has been obtained in the onPostExecute() method we need to start the ListActivity and pass it the feed we
got, we do that by bundling the feed object and attaching it to the Intent
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;
}
}
}
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);
}
}));
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>
I am using a spinner when selected starts an intent and the class that is started gets and XML feed and displays it.
I am trying to call a different XML file based on what is selected by the user. I am not sure how the value can be passed to my XMLfunctions.java and once selected can the other classes reference that data?
HERE is my Eclipse Package Download
My thourghts were to have a multidimensional array with the titles for the spinner and the coinsiding XML url:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class patriosar extends Activity {
private Button goButton;
private String array_spinner[];
String url = "http://www.patriotsar.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
Spinner areaspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array_spinner=new String[4];
array_spinner[0]="George Washington","gw.xml";
array_spinner[1]="BENJAMIN FRANKLIN","bf.xml";
array_spinner[2]="THOMAS JEFFERSON","tj.xml";
array_spinner[3]="PATRICK HENRY","ph.xml";
goButton = (Button)findViewById(R.id.goButton);
areaspinner = (Spinner) findViewById(R.id.areaspinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
areaspinner.setAdapter(adapter);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
areaspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = areaspinner.getSelectedItemPosition();
if(item != 0){
Intent myIntent = new Intent(patriosar.this, ShowXMLPAR.class);
startActivityForResult(myIntent, 0);
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
I then have a listener that calls an intent ShowXMLPAR.class when an item other then default is selected. The ShowXMLPAR class calls a function from XMLfunctions.java class and then shows the data that is returned. So the second value in the selected array item needs to be passed to to both pages I guess.
ShowXMLPAR.java:
package com.patriotsar;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.patriotsar.XMLfunctions;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ShowXMLPAR extends ListActivity {
private Button backButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
backButton = (Button)findViewById(R.id.backButton);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
Intent myIntent = new Intent(view.getContext(), patriosar.class);
startActivityForResult(myIntent, 0);
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "content"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
//
ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listlayout,
new String[] {"main_content", "name" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
}
}
XMLfunctions.java:
package com.patriotsar;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
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.methods.HttpGet;
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;
public class XMLfunctions {
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.patriotsar.com/patriot_quotes.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
Sorry I am still learning but am excited to get into more advanced (for me) programming. Any Help would be awesome.
As of now the app works but calls the same xml no matter what.
I'm not following your description very well, but if you are wanting to pass data between Activities via Intents then make sure the data you pass can either be included as an Extra, or if you prefer to send actual objects then make sure your objects implement the Parcelable interface.