How can I parse xml file from url - java

I try to get currency from this url http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml. But my parsing doesn't work. This is my code.
http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html
AndroidXMLParsingActivit.java
package com.androidhive.xmlparsing;
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 AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
// XML node keys
//static final String KEY_ITEM = "item"; // parent node
static final String KEY_ITEM = "Cube"; // parent node
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*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[] {
new String[] { KEY_NAME, KEY_ID, KEY_ID }, 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, cost);
in.putExtra(KEY_NAME, name);
//in.putExtra(KEY_COST, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
SingleMenuItemActivity.java
package com.androidhive.xmlparsing;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*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.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_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(cost);
Log.i("name", name+"");
Log.i("cost", cost+"");
}
}
XMLParser.java
package com.androidhive.xmlparsing;
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));
}
}

Original post from here.
File fXmlFile = new File("your XML file");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cube");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String currency = eElement.getAttribute("currency");
String rate = eElement.getAttribute("rate");
if(currency.isEmpty()){
continue;
}
System.out.println("Ccurrency :" + currency);
System.out.println("Rate : " + rate);
}
}
It's printing the currency and the Rate.

Just replace
File fXmlFile = new File("your XML file");
on
URL url = null;
try {
url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And code must run in AsyncTask. I will send full source code through few days.

Related

Need to change format of date in my Android app

UPDATE. I'm really struggling with the answers given (they're not bad answers, I'm just struggling)
It would really help for more detailed answers
I'm pulling in an RSS feed into my app, the pubDate is currently showing up as for example Mon, 10 Nov 2014 03:34:38 +0000.
I need it to show up in a more user friendly manner. I've looked at all the options, SimpleDateFormat..etc, I'm sort of new to Java so all previous suggestions are just going over my head, I'm looking for what I actually need to put in my code.
Code is as follows
AndroidXMLParsingActivity.java
package com.example.myapp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
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.text.Html;
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;
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://example.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "description";
static final String KEY_ID = "title";
static final String KEY_LDESC = "content:encoded";
#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_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue2(e, KEY_DESC));
map.put(KEY_LDESC, parser.getValue2(e, KEY_LDESC));
// 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_LDESC, KEY_DATE}, new int[] {
R.id.name, R.id.content_encoded, R.id.pubDate });
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 description = ((TextView) view.findViewById(R.id.description)).getText().toString();
String Ldescription = ((TextView) view.findViewById(R.id.content_encoded)).getText().toString();
String pubDate = ((TextView) view.findViewById(R.id.pubDate)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_ID, name);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_LDESC, Ldescription);
in.putExtra(KEY_DATE, pubDate);
startActivity(in);
}
});
}
}
XMLParser.java
package com.example.myapp;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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.CharacterData;
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 "";
}
public final String getElementValue2( 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 ){
if(child.getNodeType() == Node.CDATA_SECTION_NODE){
return child.getNodeValue();
}
}
}
}
return "";
//return elem.getTextContent();
}
public static String getCharacterDataFromElement(Node elem) {
Node child = elem.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
public String getValue3(Element item, String str){
NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/", str);
String ses = this.getElementValue2(n.item(0));
//return this.getElementValue2(n.item(0));
//return ses;
String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
//return Promjena(ses);
return mim;
}
/**
* 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));
}
public String getValue2(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLParser.getCharacterDataFromElement(n.item(0));
}
}
I'm not sure if you need any more information.
I'm also sure there is a lot of bad or redundant code, any help with that would be great!
Thank you very much!
String date = "Mon, 10 Nov 2014 03:34:38 +0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date _date = null;
try {
_date = sourceFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(_date .toString());
// print the Date in year month and date
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetFormat.format(_date));
You can you SimpleDateFormat class to convert friendly date as following
public String getFriendlyDayString(Date pubDate){
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(pubDate);
}
You can pass your pubDate to like this getFriendlyDateString(pubDate);
i tried replacing
String pubDate = ((TextView) view.findViewById(R.id.pubDate)).getText().toString();
with
String pubDate = "Mon, 10 Nov 2014 03:34:38 +0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date _date = null;
try {
_date = dateFormat.parse(pubDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(_date .toString());
// print the Date in year month and date
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
((TextView) view.findViewById(R.id.pubDate)).getText().toString();
didn't work...am I on the right track?

How do I pass parameter to webservice and get json datas in listview

Hi (fresher to andorid)
I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched datas from DB(sql server 2008) and bind that to android:LISTVIEW.
Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying the result based on the given value instead of that it displays all values.
Here is my webservice code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
Here is my android code(Main.java):
package com.example.cargotracking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView Id;
TextView Status;
TextView DateTime;
Button Btngetdata;
String JobNo;
EditText editText1;
ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
//JSON Node Names
private static final String TAG_CargoTrack = "Cargo";
private static final String TAG_Id = "Id";
private static final String TAG_Status = "Status";
private static final String TAG_DateTime = "DateTime";
JSONArray Cargo = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// List params = new ArrayList();
params.add(new BasicNameValuePair("JobNo","01"));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my json parser code:
package com.example.cargotracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
please help me to resolve this.
Thanks in advance

Parsing xml from website

i have an xml file located at
http://androtrends.hostingsiteforfree.com/direct.xml
i am trying to parse this xml file to use it in my program but every time the program force closes although it has no errors.i am new to java, please help!
Following is the code which i have used in XMLParser.java
public class XMLParser {
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;
}
//Parsing XML content and getting DOM element
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;
}
//Getting each xml child element value by passing element node name
public String getValue(Element item, String str) {
NodeList n = ((Document) 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 "";
}
}
The code for Channel.java is
public class Channel extends ListActivity{
String selectedmode, channelName, channelLink;
Intent urlIntent;
// All static variables
static final String DirectURL = "http://androtrends.hostingsiteforfree.com/direct.xml";
static final String FlashURL="http://androtrends.hostingsiteforfree.com/direct.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_Channel = "channel";
static final String KEY_Link = "link";
String xml;
Toast toast;
ArrayList<HashMap<String, String>> menuItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.channels);
selectedmode=getIntent().getExtras().getString("key");
urlIntent=new Intent(Intent.ACTION_VIEW);
Toast.makeText(this, "Wait 60 secs to load the stream...", Toast.LENGTH_LONG).show();
updatechannels();
ListView lv=getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
channelName= ((TextView) view.findViewById(R.id.channelName)).getText().toString();
channelLink= ((TextView) view.findViewById(R.id.channelLink)).getText().toString();
urlIntent.setData(Uri.parse(channelLink));
toast.show();
startActivity(urlIntent);
}
});
}
private void updatechannels() {
// TODO Auto-generated method stub
menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
if (selectedmode.equalsIgnoreCase("direct"))
{
xml = parser.getXmlFromUrl(DirectURL); // getting XML
}else
{
xml = parser.getXmlFromUrl(FlashURL);
}
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_Channel, parser.getValue(e, KEY_Channel));
map.put(KEY_Link, parser.getValue(e, KEY_Link));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_Channel, KEY_Link }, new int[] {
R.id.channelName, R.id.channelLink });
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
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.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://androtrends.hostingsiteforfree.com/direct.xml";
// Progress dialog
ProgressDialog pDialog;
ArrayList<String> title;
ArrayList<String> description;
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>();
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("channel");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
System.out.println("channel : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("link");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
description.add(""+ ((Node) nameList1.item(0)).getNodeValue());
System.out.println("link : "+ ((Node) nameList1.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();
String value = result;
// Log.v("URL Res- - - -", ""+value);
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 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);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+description.get(position));
return view;
}
}
}

Parsing two elements with the same name - Pull Parser

My last question was badly phrased - I am attempting to parse the following xml:
I am having issues parsing the elements inside congestion location:
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
<tns:order>6</tns:order>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
<tns:order>2</tns:order>
</tns:congestionLocations>
<tns:id>130</tns:id>
<tns:offline>false</tns:offline>
<tns:underMaintenance>false</tns:underMaintenance>
</tns:camera>
Using XMLPullParser, I can read the id, offline, etc elements. This works fine. I've written my code to parse the XML below:
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
FileInputStream fis = ctx.openFileInput("CameraSites.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// If we are starting a new <site> block we need
//a new CameraClass object to represent it
curCameraClass = new CameraClass();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// if </site> then we are done with current Site
// add it to the list.
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_ID)) {
curCameraClass.setID(curText);
} else if (tagname.equalsIgnoreCase(KEY_MAIN)) {
curCameraClass.setMAIN(curText);
}
break;
default:
break;
}
//move on to next iteration
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return CameraSites;
}
My question is, how would I parse the congestion and direction elements found in the congestion locations? I am parsing these into a get/set method with a class (CameraClass).
Thanks in advance!
Here is the code with your xml..
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
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.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.util.Log;
import android.view.Menu;
public class FileActivity extends Activity {
// Progress dialog
ProgressDialog pDialog;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
String data = "<tns:camera>"
+" <tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Eastbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Westbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:description>Bond St looking east</tns:description>"
+"<tns:direction>Eastbound</tns:direction>"
+"<tns:group>SH16-North-Western</tns:group>"
+"<tns:lat>-36.869</tns:lat>"
+"<tns:lon>174.746</tns:lon>"
+"<tns:name>SH16 1 Bond St</tns:name>"
+"<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>"
+" </tns:camera>";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(data).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 data;
// constructor
public XmlParsing(String data) {
this.data = data;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(FileActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
FileOutputStream out = openFileOutput("hello.txt",Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
BufferedReader input = new BufferedReader(new InputStreamReader(openFileInput("hello.txt")));
StringBuffer inLine = new StringBuffer();
String text;
while ((text = input.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
input.close();
String finalData =inLine.toString();
InputStream is = new ByteArrayInputStream(finalData.getBytes("UTF-8"));
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
Log.v("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((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();
}
}
}
From log you can see the result...

http request asynctask in onclicklistener

i want to start my Asynctask:
package com.androidhive.xmlparsing;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class onoff extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private boolean error = false;
private Context mContext;
private int NOTIFICATION_ID = 1;
private Notification mNotification;
private NotificationManager mNotificationManager;
public onoff(Context context){
this.mContext = context;
//Get the notification manager
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
protected void onPreExecute() {
createNotification("Data download is in progress","");
}
protected String doInBackground(String... urls) {
String URL = null;
String param1 = null;
String param2 = null;
String param3 = null;
try {
//URL passed to the AsyncTask
URL = urls[0];
param1 = urls[1];
param2 = urls[2];
param3 = urls[3];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//Any other parameters you would like to set
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("token",param1));
nameValuePairs.add(new BasicNameValuePair("deviceid",param2));
nameValuePairs.add(new BasicNameValuePair("actionid",param3));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Response from the Http Request
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
//Check the Http Request for success
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
Log.d("test", content);
}
else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
error = true;
cancel(true);
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
error = true;
cancel(true);
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();
error = true;
cancel(true);
}
return content;
}
protected void onCancelled() {
createNotification("Es ist ein Problem aufgetreten(2)!",content);
}
protected void onPostExecute(String content) {
if (error) {
createNotification("Es ist ein Problem aufgetreten(1)!",content);
} else {
createNotification("Gerät erfolgreich geschaltet(3)!","");
}
}
private void createNotification(String contentTitle, String contentText) {
//Build the notification using Notification.Builder
Notification.Builder builder = new Notification.Builder(mContext)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setAutoCancel(true)
.setContentTitle(contentTitle)
.setContentText(contentText);
//Get current notification
mNotification = builder.getNotification();
//Show the notification
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
}
in a onclicklistener on a ListActivity:
package com.androidhive.xmlparsing;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
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_COST);
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) {
String[] url={"http://url.de/", "url","/" + KEY_ID,"/" + KEY_COST};
new onoff(this).execute(url);
}
});
Button lbloff = (Button)findViewById(R.id.off);
lbloff.getText().toString();
lbloff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
lblid.setText(deviceid);
lblon.setText(on);
lbloff.setText(off);
}
}
the xmlparser:
package com.androidhive.xmlparsing;
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));
}
}
but i get an erron on onoff(this)? The constructor onoff is undefined
i want to start a http request when the button is clicked.
can someone help me?
In new onoff(this), this refers to the instance of OnClickListener.
Change
new onoff(this).execute(url);
with
new onoff(SingleMenuItemActivity.this).execute(url);

Categories

Resources