Android XML parsing listview - android

I using this tutorial http://www.androidbegin.com/tutorial/android-xml-parse-images-and-texts-tutorial/ to reaching XML parsing,if I want to change the url to this one http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml ,how to do that? Because the xml format are different.If there is a similar question of this please inform me.Thanks.
There is a tag in each listitem but my url only 'Infos' at begin which includes all tags.
MainActivity.java
package eason.xml;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
// Declare Variables
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "Id";
static String NAME = "Name";
static String WEBSITE = "Website";
static String PICTURE1 = "Picture";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadXML().execute();
}
// DownloadJSON AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {
private void parseRequestResultXML(InputStream stream) {
arraylist=new ArrayList<HashMap<String,String>>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(stream, null);
HashMap<String, String> map = null;
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (parser.getEventType()) {
case XmlPullParser.START_DOCUMENT:
//Log.i("TAG", " Start document " + parser.getName());
break;
case XmlPullParser.START_TAG:
//Log.i("TAG", " Start tag " + parser.getName());
String tag=parser.getName();
if(tag.equals("Info")){ //read values from Info tag
Log.i("TAG","reading info");
ID=parser.getAttributeValue(null, "Id");
NAME=parser.getAttributeValue(null, "Name");
WEBSITE=parser.getAttributeValue(null, "Website");
PICTURE1=parser.getAttributeValue(null,"Picture1");
//do same for other values
map = new HashMap<String, String>();
map.put("Id", ID);
map.put("Name", NAME);
map.put("Website", WEBSITE);
arraylist.add(map);
}
break;
case XmlPullParser.END_TAG:
//Log.i("TAG", " End tag " + parser.getName());
break;
default:
break;
}
eventType=parser.next(); //get next event type
}
//reading all values from list
for (Map<String,String> e : arraylist) {
Log.d("TAG"," Row ID "+e.get("Id")+" Name "+e.get("Name")+" Website "+e.get("Website")+" Picture1 "+e.get("Picture1"));
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android XML Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
InputStream stream = parser.getInputStreamFromUrl("http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml");
if (stream != null) {
try {parseRequestResultXML(stream);
stream.close();}catch(IOException e1) {
e1.printStackTrace();
}
}return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}}
ListViewAdapter
package eason.xml;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView NAME;
TextView START;
TextView WEBSITE;
ImageView Picture1;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
NAME = (TextView) itemView.findViewById(R.id.rank);
START = (TextView) itemView.findViewById(R.id.country);
WEBSITE = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
Picture1 = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
NAME.setText(resultp.get(MainActivity.ID));
START.setText(resultp.get(MainActivity.NAME));
WEBSITE.setText(resultp.get(MainActivity.WEBSITE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.PICTURE1), Picture1);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("Id", resultp.get(MainActivity.ID));
// Pass all data country
intent.putExtra("Name", resultp.get(MainActivity.NAME));
// Pass all data population
intent.putExtra("Website",
resultp.get(MainActivity.WEBSITE));
// Pass all data flag
intent.putExtra("Picture1", resultp.get(MainActivity.PICTURE1));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
XML parser
package eason.xml;
import android.util.Log;
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.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class XMLParser {
public XMLParser() {
}
// Retrive XML from URL
public String getXmlFromUrl(String url) {
String xml = null;
try {
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;
}
// Retrive 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 doc;
}
// Retrive Node 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 "";
}
// Retrive Node Value
public InputStream getInputStreamFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Change the URL in getXmlFromUrl() and then change the keys in parser.getValue(e, **RANK**). Whatever your format is, you need to specify the keys to get the data and then save accordingly.

In that tutorial Author is reading values from TEXT tag of XML. But in your case you need to get values from there attribute name.
private void parseRequestResultXML(InputStream stream) {
arraylist=new ArrayList<HashMap<String,String>>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(stream, null);
HashMap<String, String> map = null;
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (parser.getEventType()) {
case XmlPullParser.START_DOCUMENT:
//Log.i("TAG", " Start document " + parser.getName());
break;
case XmlPullParser.START_TAG:
//Log.i("TAG", " Start tag " + parser.getName());
String tag=parser.getName();
if(tag.equals("Info")){ //read values from Info tag
Log.i("TAG","reading info");
String id=parser.getAttributeValue(null, "Id");
String name=parser.getAttributeValue(null, "Name");
String website=parser.getAttributeValue(null, "Website");
//do same for other values
map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("website", website);
arraylist.add(map);
}
break;
case XmlPullParser.END_TAG:
//Log.i("TAG", " End tag " + parser.getName());
break;
default:
break;
}
eventType=parser.next(); //get next event type
}
//reading all values from list
for (Map<String,String> e : arraylist) {
Log.d("TAG"," Row ID "+e.get("id")+" Name "+e.get("name")+" Website "+e.get("website"));
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
UPDATED:
Add this method in XMLParser.java
public InputStream getInputStreamFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
In doInBackground
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
InputStream stream = parser.getInputStreamFromUrl("http://www.androidbegin.com/tutorial/xmlparseimgtxt.xml");
if (stream != null){
parseRequestResultXML(stream);
stream.close();
}

Related

Search in listview and show the result

how is it possible to parse some Json Data from web and put them in a listview.
Inside of them i would like to search something, I'm searching now for a while in the internet but I wasn't successfull.
I still can Parse JSON and pu them in a listview but how can I search?
Here my Code
MainAct.:
import java.util.ArrayList;
import java.util.HashMap;
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.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 ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "*****";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
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();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
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();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
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 "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.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) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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;
}
}
List<list> varr = yourlist;
for (list result : varr) {
// action such as.. if result
}
hope this help

how to convert html string in java string

I'm retrieving an XML from the Google Maps Directions API.
The result is something like this:
<DirectionsResponse>
<status>OK</status>
<route>
<summary>I-40 W</summary>
<leg>
<step>
<travel_mode>DRIVING</travel_mode>
<start_location>
<lat>41.8507300</lat>
<lng>-87.6512600</lng>
</start_location>
<end_location>
<lat>41.8525800</lat>
<lng>-87.6514100</lng>
</end_location>
<polyline>
<points>a~l~Fjk~uOwHJy#P</points>
</polyline>
<duration>
<value>19</value>
<text>1 min</text>
</duration>
<html_instructions>Head <b>north</b> on <b>S Morgan St</b> toward <b>W Cermak Rd</b></html_instructions>
<distance>
<value>207</value>
<text>0.1 mi</text>
</distance>
</step>
...
... additional steps of this leg
...
... additional legs of this route
<duration>
<value>74384</value>
<text>20 hours 40 mins</text>
</duration>
<distance>
<value>2137146</value>
<text>1,328 mi</text>
</distance>
<start_location>
<lat>35.4675602</lat>
<lng>-97.5164276</lng>
</start_location>
<end_location>
<lat>34.0522342</lat>
<lng>-118.2436849</lng>
</end_location>
<start_address>Oklahoma City, OK, USA</start_address>
<end_address>Los Angeles, CA, USA</end_address>
<copyrights>Map data ©2010 Google, Sanborn</copyrights>
<overview_polyline>
<points>a~l~Fjk~uOnzh#vlbBtc~#tsE`vnApw{A`dw#~w\|tNtqf#l{Yd_Fblh#rxo#b}#xxSfytAblk#xxaBeJxlcBb~t#zbh#jc|Bx}C`rv#rw|#rlhA~dVzeo#vrSnc}Axf]fjz#xfFbw~#dz{A~d{A|zOxbrBbdUvpo#`cFp~xBc`Hk#nurDznmFfwMbwz#bbl#lq~#loPpxq#bw_#v|{CbtY~jGqeMb{iF|n\~mbDzeVh_Wr|Efc\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg#|kHntyArpb#bijCk_Kv~eGyqTj_|#`uV`k|DcsNdwxAott#r}q#_gc#nu`CnvHx`k#dse#j|p#zpiAp|gEicy#`omFvaErfo#igQxnlApqGze~AsyRzrjAb__#ftyB}pIlo_BflmA~yQftNboWzoAlzp#mz`#|}_#fda#jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC</points>
</overview_polyline>
<optimized_waypoint_index>0</optimized_waypoint_index>
<optimized_waypoint_index>1</optimized_waypoint_index>
<bounds>
<southwest>
<lat>34.0523600</lat>
<lng>-118.2435600</lng>
</southwest>
<northeast>
<lat>41.8781100</lat>
<lng>-87.6297900</lng>
</northeast>
</bounds>
</route>
</DirectionsResponse>
I try to print the value of the tag , but it shows also the <b> or the <div>.
Thus I try to use the class StringEscapeUtils like this:
StringEscapeUtils.escapeHtml4(KEY_HTML_INSTRUCTIONS);
but it doesn't work.
I use this XML Parser:
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 {
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;
}
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 "";
}
}
And here is the activity that shows the information taken from the XML:
import maps.XMLParser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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 DirectionsActivity extends ListActivity {
String url = "";
XMLParser parser;
String xml = "";
ArrayList<HashMap<String, String>> menuItems;
// All static variables
static final String KEY_STEP = "step"; // parent node
static final String KEY_HTML_INSTRUCTIONS = "html_instructions";
static final String KEY_DURATION = "duration";
static final String KEY_DISTANCE = "distance";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = this.getIntent();
url = intent.getExtras().getString("url");
System.out.println("---------------" + url);
menuItems = new ArrayList<HashMap<String, String>>();
parser = new XMLParser();
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem 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.instruction)).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(), SingleMenuItemActivity.class);
in.putExtra(KEY_HTML_INSTRUCTIONS, name);
// in.putExtra(KEY_COST, cost);
// in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask<String, Void, String>{
ListAdapter adapter;
private ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DirectionsActivity.this);
pd.setTitle("Processing...");
pd.setMessage("Calcolo direzione in corso dalla posizione corrente...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = parser.getXmlFromUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_STEP);
// 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
String escapeKeyHtmlInstructions = StringEscapeUtils.escapeXml(KEY_HTML_INSTRUCTIONS);
// KEY_HTML_INSTRUCTIONS.replaceAll("\\<.*?>", "");
map.put(KEY_HTML_INSTRUCTIONS, parser.getValue(e, escapeKeyHtmlInstructions));
// map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
// map.put(KEY_DISTANCE, "Rs." + parser.getValue(e, KEY_DISTANCE));
// map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
adapter = new SimpleAdapter(DirectionsActivity.this, menuItems,R.layout.list_item,
new String[] { KEY_HTML_INSTRUCTIONS}, new int[] {
R.id.instruction});
setListAdapter(adapter);
pd.dismiss();
}
}
}
How can I fix that? Is there other libraries I can use?
I was able to fix that by adding this code in the activity:
instructionValue = parser.getValue(e, KEY_HTML_INSTRUCTIONS);
instructionValueFixed = Html.fromHtml(instructionValue).toString();
map.put(KEY_HTML_INSTRUCTIONS, instructionValueFixed);
you should use XML parser for such type of data. As it is XML not HTML you can use any parser like DOM , SAX or any, that you can get the data properly and save each tag data separately..

How to get the distance and duration from Google Directions API

I'm developing an Android app in which I created an activity that shows a list of directions taken from Google Directions API.
The url used is something like this: http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false
And the result is something like this:
<DirectionsResponse>
<status>OK</status>
<route>
<summary>I-40 W</summary>
<leg>
<step>
<travel_mode>DRIVING</travel_mode>
<start_location>
<lat>41.8507300</lat>
<lng>-87.6512600</lng>
</start_location>
<end_location>
<lat>41.8525800</lat>
<lng>-87.6514100</lng>
</end_location>
<polyline>
<points>a~l~Fjk~uOwHJy#P</points>
</polyline>
<duration>
<value>19</value>
<text>1 min</text>
</duration>
<html_instructions>Head <b>north</b> on <b>S Morgan St</b> toward <b>W Cermak Rd</b></html_instructions>
<distance>
<value>207</value>
<text>0.1 mi</text>
</distance>
</step>
...
... additional steps of this leg
...
... additional legs of this route
<duration>
<value>74384</value>
<text>20 hours 40 mins</text>
</duration>
<distance>
<value>2137146</value>
<text>1,328 mi</text>
</distance>
<start_location>
<lat>35.4675602</lat>
<lng>-97.5164276</lng>
</start_location>
<end_location>
<lat>34.0522342</lat>
<lng>-118.2436849</lng>
</end_location>
<start_address>Oklahoma City, OK, USA</start_address>
<end_address>Los Angeles, CA, USA</end_address>
<copyrights>Map data ©2010 Google, Sanborn</copyrights>
<overview_polyline>
<points>a~l~Fjk~uOnzh#vlbBtc~#tsE`vnApw{A`dw#~w\|tNtqf#l{Yd_Fblh#rxo#b}#xxSfytAblk#xxaBeJxlcBb~t#zbh#jc|Bx}C`rv#rw|#rlhA~dVzeo#vrSnc}Axf]fjz#xfFbw~#dz{A~d{A|zOxbrBbdUvpo#`cFp~xBc`Hk#nurDznmFfwMbwz#bbl#lq~#loPpxq#bw_#v|{CbtY~jGqeMb{iF|n\~mbDzeVh_Wr|Efc\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg#|kHntyArpb#bijCk_Kv~eGyqTj_|#`uV`k|DcsNdwxAott#r}q#_gc#nu`CnvHx`k#dse#j|p#zpiAp|gEicy#`omFvaErfo#igQxnlApqGze~AsyRzrjAb__#ftyB}pIlo_BflmA~yQftNboWzoAlzp#mz`#|}_#fda#jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC</points>
</overview_polyline>
<optimized_waypoint_index>0</optimized_waypoint_index>
<optimized_waypoint_index>1</optimized_waypoint_index>
<bounds>
<southwest>
<lat>34.0523600</lat>
<lng>-118.2435600</lng>
</southwest>
<northeast>
<lat>41.8781100</lat>
<lng>-87.6297900</lng>
</northeast>
</bounds>
</route>
</DirectionsResponse>
In every item of the list I want to show the information contained in <html_instructions>, <text> child of <distance> and <text> child of <duration>.
I was able to obtain the value of <html_instructions> tag, using this parser:
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 {
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;
}
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 "";
}
}
How can I modify this parser in order to shows also the values of the other two tags?
I was able to fix that by adding another method in XMLParser class:
public String getSecondValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(1));
}
and here is the usage in the activity:
import java.util.ArrayList;
import java.util.HashMap;
import maps.XMLParser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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 DirectionsActivity extends ListActivity {
String url = "";
XMLParser parser;
String xml = "";
ArrayList<HashMap<String, String>> menuItems;
// All static variables
static final String KEY_STEP = "step"; // parent node
static final String KEY_HTML_INSTRUCTIONS = "html_instructions";
static final String KEY_DURATION = "duration";
static final String KEY_DISTANCE = "distance";
static final String KEY_TEXT = "text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = this.getIntent();
url = intent.getExtras().getString("url");
System.out.println("---------------" + url);
menuItems = new ArrayList<HashMap<String, String>>();
parser = new XMLParser();
DownloadTask downloadTask = new DownloadTask();
// Start downloading XML data from Google Directions API
downloadTask.execute(url);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String instruction = ((TextView) view.findViewById(R.id.instruction)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_HTML_INSTRUCTIONS, instruction);
startActivity(in);
}
});
}
/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask<String, Void, String>{
ListAdapter adapter;
private ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DirectionsActivity.this);
pd.setTitle("Processing...");
pd.setMessage("Calcolo direzione in corso dalla posizione corrente...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = parser.getXmlFromUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_STEP);
// looping through all item nodes <step>
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
String escapedKeyHtmlInstructions = StringEscapeUtils.escapeHtml4(KEY_HTML_INSTRUCTIONS);
// KEY_HTML_INSTRUCTIONS.replaceAll("\\<.*?>", "");
map.put(KEY_HTML_INSTRUCTIONS, parser.getValue(e, escapedKeyHtmlInstructions));
map.put(KEY_DURATION, parser.getValue(e, KEY_TEXT));
map.put(KEY_DISTANCE, parser.getSecondValue(e, KEY_TEXT));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
adapter = new SimpleAdapter(DirectionsActivity.this, menuItems,R.layout.list_item,
new String[] { KEY_HTML_INSTRUCTIONS, KEY_DURATION, KEY_DISTANCE}, new int[] {
R.id.instruction, R.id.duration, R.id.distance});
setListAdapter(adapter);
pd.dismiss();
}
}
}

Parse Imagelink in Cdata description tag Dom parsing

I want to retrieve the image link inside the description tag, my tags are all working, here is the sample of description tag:
[http://news.instaforex.com/analytics/rss][1]
I want to retrieve the image link or to show the image. My question is how to that base on my code below?
mainactivity
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://news.instaforex.com/analytics/rss";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayList<HashMap<String, Spanned>> menuItems = new ` ArrayList<HashMap<String, Spanned>>();
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, Spanned> map = new HashMap<String, Spanned>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
String description = parser.getValue(e, KEY_DESCRIPTION);;
int index = description.indexOf("The material has been provided by InstaForex Company", 0);
description = description.substring(0, index-1);
map.put(KEY_DESCRIPTION, Html.fromHtml(description));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_TITLE, KEY_PUBDATE }, new int[] {
R.id.name, R.id.cost });
setListAdapter(adapter);
((BaseAdapter) adapter).notifyDataSetChanged();
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String title = menuItems.get(position).get(KEY_TITLE).toString();
String pubDate = menuItems.get(position).get(KEY_PUBDATE).toString();
String description= menuItems.get(position).get(KEY_DESCRIPTION).toString();
System.out.println("PubDate==>"+pubDate+"\n Description===>"+description);
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_PUBDATE, pubDate);
in.putExtra(KEY_DESCRIPTION, description);
startActivity(in);
}
});
}
}
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.text.Html;
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();
dbf.setCoalescing(true);
dbf.setNamespaceAware(true);
if (dbf.isNamespaceAware()==Boolean.TRUE) {
dbf.setNamespaceAware(Boolean.FALSE);
}
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 || child.getNodeType() == Node.CDATA_SECTION_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));
}
}

progress dialog keeps on displaying

I have written a long code in android and which displays a progress dialog when the restaurant list is loaded into the listview. Now the problem is that its working fine when restaurant list is loaded again on users filter changes but only at the first time. it just keeps on displaying even if the listview is populated and user has to manually dismiss it pressing the back button of deivce. I dont knw where to write pg.dismiss() in this case. Posting my code here . plz advise me..
package com.Refinedymapps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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 android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Restaurantlist extends Activity implements OnClickListener, OnItemSelectedListener {
ProgressDialog pg;
private ImageButton imgbtn;
private ListView restaurant;
private TextView city;
String sendid,flagdopost="",linkurl;
LocationManager locationManger;
Geocoder gc;
Bundle bundle;
private int j=0;
private Spinner cuisine,area;
static ArrayList<HashMap<String,String>> customlist= new ArrayList<HashMap<String,String>>();
private String asynctaskflag="",cuisineval,areaval;
List<String> tempareanamelist,tempcuisinenamelist,areanamelist,cuisinelist,cuisineidlist,restaurantnames,areanames,restaurantidlist,originalcuisinelist,originalarealist;
String str,coun,stat,cid,sid,cityid,cityname;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurantlisting);
linkurl=getResources().getString(R.string.linkurl);
city=(TextView)findViewById(R.id.textviewcity);
cuisine=(Spinner)findViewById(R.id.spncuisine);
area=(Spinner)findViewById(R.id.spnarea);
restaurant=(ListView)findViewById(R.id.lstrestaurant);
imgbtn=(ImageButton)findViewById(R.id.imageButton1);
bundle = this.getIntent().getExtras();
imgbtn.setImageResource(R.drawable.searchloc);
asynctaskflag="init";
new Thetask().execute(asynctaskflag,null,null);
imgbtn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent newlocintent=new Intent(Restaurantlist.this,Restaurantlistdisplay.class);
startActivity(newlocintent);
}
});
restaurant.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getBaseContext(), "resname"+restaurantnames.get(arg2)+"areaname"+areanames.get(arg2), 10).show();
String[] getid={"itemclick",restaurantnames.get(arg2),areanames.get(arg2)};
new Thetask().execute(getid);
}
});
}
public void populateReslist()
{
Log.i("inside populatereslist","value of j is:"+j);
for(int i=0;i<restaurantnames.size();i++)
{
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Restaurant Name",restaurantnames.get(i).toString());
temp.put("Area Name", areanames.get(i).toString());
customlist.add(temp);
}
}
public List<String> getAreanames(String cityid)
{
String list = null;
areanamelist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/areas/");
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Closing the input stream will trigger connection release
list= sb.toString();
Log.i("areaname xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Area");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("areaName"))
{
areanamelist.add(property.getFirstChild().getNodeValue());
}
else
{
}
}
}
//Log.i("areaname list in getAreas method", areanamelist.toString());
return areanamelist;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public List<String> getCuisines(String cityid)
{
String list = null;
cuisinelist=new ArrayList<String>();
cuisineidlist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/cuisines/");
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Closing the input stream will trigger connection release
list= sb.toString();
Log.i("cuisinename xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Cuisine");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("cuisineName"))
{
cuisinelist.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("cuisineId"))
{
cuisineidlist.add(property.getFirstChild().getNodeValue());
}
}
}
Log.i("getcuisine cuisinelist",cuisinelist.toString());
return cuisinelist;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void firequery()
{
String url = null;
if(cuisineval=="*" && areaval=="*")
{
url=linkurl+"/ymaws/resources/restaurant/"+cityid+"/restaurants";
}
else if(cuisineval!="*" && areaval=="*")
{
for(int i=0;i<originalcuisinelist.size();i++)
{
Log.i("cuisinelist original item is",""+originalcuisinelist.get(i));
Log.i("cuisineidlist is",cuisineidlist.toString());
if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
{
Log.i("cuisineid selected is",""+cuisineidlist.get(i));
url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i);
}
}
}
else if(cuisineval=="*" && areaval!="*")
{
url = linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&areanm="+area.getSelectedItem().toString();
}
else
{
for(int i=0;i<originalcuisinelist.size();i++)
{
if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
{
url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i)+"&areanm="+area.getSelectedItem().toString();
}
}
}
getResult(url);
}
public void getResult(String url)
{
String list = null;
restaurantnames=new ArrayList<String> ();
areanames=new ArrayList<String>();
restaurantidlist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
Log.i("url is","url:"+url.toString());
final HttpGet req=new HttpGet(url.replaceAll(" ", "%20"));
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
list= sb.toString();
Log.i("list xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
if(list!=null)
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("resLovData");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("locName"))
{
restaurantnames.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("areaName"))
{
areanames.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("locId"))
{
restaurantidlist.add(property.getFirstChild().getNodeValue());
}
}
}
}
else
{
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public class Thetask extends AsyncTask<String, Void, Void>
{
String x,y;
#Override
public void onPreExecute()
{
pg =new ProgressDialog(Restaurantlist.this);
pg.setMessage("fetching info....");
pg.setIndeterminate(true);
pg.setCancelable(true);
Log.i("inside preexecute","in pre execute");
pg.show();
}
public Void doInBackground(String... params)
{
if(params[0].equalsIgnoreCase("init"))
{
Log.i("inside doinbackground 1st",flagdopost);
cid=bundle.getString("cid");
sid=bundle.getString("sid");
cityid=bundle.getString("cityid");
cityname=bundle.getString("cityname");
originalcuisinelist=new ArrayList<String>();
originalcuisinelist=getCuisines(cityid);
tempcuisinenamelist = getCuisines(cityid);
tempcuisinenamelist.add(0,"All");
originalarealist=new ArrayList<String>();
originalarealist=getAreanames(cityid);
tempareanamelist=getAreanames(cityid);
tempareanamelist.add(0,"All");
Log.i("area are",tempareanamelist.toString());
flagdopost="init";
Log.i("inside doinbackground 1st",flagdopost);
}
else if(params[0].equalsIgnoreCase(""))
{
flagdopost="";
j++;
if(j!=1)
{
firequery();
flagdopost="itemselected";
Log.i("inside doinbackground 2nd",flagdopost);
}
}
else if(params[0].equalsIgnoreCase("itemclick"))
{
x=params[1];
y=params[2];
for(int i=0;i<restaurantidlist.size();i++)
{
if((params[1].toString()).equalsIgnoreCase(restaurantnames.get(i)))
{
sendid=restaurantidlist.get(i);
}
}
Log.i("in do in backgroung idforbundle is", sendid);
flagdopost="itemclicked";
}
return null;
}
public void onPostExecute(Void result)
{
if(flagdopost.equalsIgnoreCase("init"))
{
city.setText(cityname);
ArrayAdapter<String> adaptercuisine=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempcuisinenamelist);
adaptercuisine.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<String> adapterarea=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempareanamelist);
adapterarea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
area.setAdapter(adapterarea);
area.setSelection(0);
cuisine.setAdapter(adaptercuisine);
cuisine.setSelection(0);
area.setOnItemSelectedListener(Restaurantlist.this);
cuisine.setOnItemSelectedListener(Restaurantlist.this);
}
else if(flagdopost.equalsIgnoreCase("itemselected"))
{
customlist.clear();
populateReslist();
restaurant.invalidateViews();
restaurant.setAdapter(new SimpleAdapter(Restaurantlist.this,customlist,R.layout.customlistrow,new String[] {"Restaurant Name","Area Name"},
new int[] {R.id.tvresname,R.id.tvareaname})
{
#Override
public View getView(int position, View convertView,ViewGroup parent)
{
View view =super.getView(position, convertView, parent);
return view;
}
});
}
else if(flagdopost.equalsIgnoreCase("itemclicked"))
{
Bundle bundle=new Bundle();
bundle.putString("locid",sendid);
Toast.makeText(getBaseContext(), "locId in dopost new one"+sendid, 10).show();
Intent resdetail = new Intent(Restaurantlist.this,Restaurantdetail.class);
resdetail.putExtras(bundle);
startActivity(resdetail);
}
pg.dismiss();
}
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
switch(arg0.getId())
{
case R.id.spncuisine:
asynctaskflag="";
if(cuisine.getSelectedItem().toString()!="All")
{
cuisineval=cuisine.getSelectedItem().toString();
}
else
{
cuisineval="*";
}
new Thetask().execute(asynctaskflag,null,null);
break;
case R.id.spnarea:
asynctaskflag="";
if(area.getSelectedItem().toString()!="All")
{
areaval=area.getSelectedItem().toString();
}
else
{
areaval="*";
}
new Thetask().execute(asynctaskflag,null,null);
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Try declaring your ProgressDialog inside the AsyncTask. Instead of as a Activity member variable.
public class Thetask extends AsyncTask<String, Void, Void>
{
ProgressDialog pg = null;
String x,y;
#Override
public void onPreExecute()
...

Categories

Resources