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()
...
Related
/* Here the last parameter is taken from edittext but it is not adding input from
edittext */ Please check:
http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/CBS/NOIDA/ADMIN
package com.example.administrator.spinnerval;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class SalesActivity extends AppCompatActivity {
StringBuffer buffer = new StringBuffer();
List<String> salesPeName = new ArrayList<String>();
HttpURLConnection connection;
BufferedReader reader;
ProgressDialog pdLoading;
String username = "CBS";
String password = "NOIDA";
String city="" ;
String myurl;
ArrayAdapter adapter;
URL url;
AutoCompleteTextView acTextView;
//String url="http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales);
acTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete2);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String)parent.getItemAtPosition(position);
// city=(String)parent.getItemAtPosition(position);
city=acTextView.getText().toString();
}
});
myurl="http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo";
String res = new StringBuilder(14).append(myurl).append("/").append(username).append("/").append(password).toString();
String result=new StringBuilder(14).append(res).append("/").append(city).toString();
try {
url=new URL(result);
Log.d("url",url.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
adapter = new
ArrayAdapter(this, android.R.layout.simple_list_item_1, salesPeName);
//acTextView.setAdapter(adapter);
new SalesTask().execute(city);
}
private class SalesTask extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params) {
try {
//url = new URL("http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/"+username+"/"+password+"/"+city);
connection = (HttpURLConnection) url.openConnection();
Log.e("url reference value",url.toString());
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
Log.d("bufferData", buffer.toString());
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String jsonString = buffer.toString();
// Log.e("Final Json that we have", jsonString);
JSONObject obj = null;
try {
obj = new JSONObject(jsonString);
JSONObject obj1 = obj.getJSONObject("GetBPSalesPersonResult");
JSONArray jArray = obj1.getJSONArray("BPResult");
for (int i = 0; i <= jArray.length(); i++) {
salesPeName.add(jArray.getJSONObject(i).getString("SALES_PERSON_NO"));
Log.e("Location",salesPeName.toString());
acTextView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Logcat is printing url as :
url: http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/CBS/NOIDA/
Not sure if I understood your question correctly, but you are adding undeclared variables to the url. I think it should be:
URL url = new URL("http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/"+cbs+"/"+city+"/"+saleP);
The problem is that you create the Url on in onCreate, at witch time city="", and you change the city in onItemClick: city=acTextView.getText().toString(), you need to generate the URL in onItemClick and call new SalesTask().execute(city); not right away
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String)parent.getItemAtPosition(position);
city = acTextView.getText().toString();
url = new URL(new StringBuilder(myurl).append("/").append(username).append("/").append(password).append("/").append(city).toString());
new SalesTask().execute(city);
}
});
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();
}
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.
I am beginner for Android. I want to send the data to my PHP page. but here i m trying to toast that post values. but there is no response. Plz help me.
My Code is:
public class send_msgActivity extends Activity{
//static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_msg);
Button btn_ok = (Button) findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText1 = (EditText)findViewById(R.id.sender);
String S_name = editText1.getText().toString();
EditText editText2 = (EditText)findViewById(R.id.reciever);
String S_email = editText2.getText().toString();
postData(S_name,S_email);
}
});
};
public void postData(String name,String email) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.URL.com/yourpage.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Fname", name));
nameValuePairs.add(new BasicNameValuePair("Femail", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost, new BasicResponseHandler());
HttpResponse response = httpclient.execute(httppost);
String reverseString = response.toString();
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Use this example how to code HTTPpost method
package com.example.login;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;a
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class pdf extends Activity
{
public boolean connect=false,logged=false;
public String db_select;
ListView l1;
String mPwd,UName1="Success",UName,ret;
public Iterator<String> itr;
private String SERVICE_URL = "http://61.12.7.197:8080/Agero/person/pdf";
private String SERVICE_URL1 = "http://61.12.7.197:8080/Agero/person/url";
//private final String SERVICE_URL = "http://10.1.1.138:8080/Agero/person/pdf";
//private final String SERVICE_URL1 = "http://10.1.1.138:8080/Agero/person/url";
private final String TAG = "Course";
ArrayList<String> todoItems;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayAdapter<String> aa;
public List<String> list1=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf);
l1 = (ListView)findViewById(R.id.list);
todoItems = new ArrayList<String>();
aa = new ArrayAdapter<String>(this,R.layout.list_row,R.id.title,todoItems);
l1.setAdapter(aa);
todoItems.clear();
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user();
//display("hi");
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String name=(String)parent.getItemAtPosition(position);
/*Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show();
Intent i = new Intent(getBaseContext(),Webview.class);
i.putExtra("USERNAME", name);
startActivity(i);*/
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user1(name);
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
}
});
}
public void display(String msg)
{
Toast.makeText(pdf.this, msg, Toast.LENGTH_LONG).show();
}
private void validat_user()
{
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");
// wst.addNameValuePair("State", stg1);
// wst.addNameValuePair("Emp_PWD", stg2);
// db_select=stg1;
//display("I am");
wst.execute(new String[] { SERVICE_URL });
//display(SERVICE_URL);
}
private void validat_user1(String stg1)
{
db_select=stg1;
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Loading...");
wst.addNameValuePair1("PDF_NAME", stg1);
wst.execute(new String[] { SERVICE_URL1 });
}
#SuppressWarnings("deprecation")
public void no_net()
{
display( "No Network Connection");
final AlertDialog alertDialog = new AlertDialog.Builder(pdf.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
//alertDialog.setIcon(R.drawable.error_info);
alertDialog.setCancelable(false);
alertDialog.setButton("Close", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.cancel();
pdf.this.finish();
System.exit(0);
}
});
alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
display( "Accessing local DataBase.....");
alertDialog.cancel();
}
});
alertDialog.show();
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair1(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
} catch (Exception e) {
display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{ //display("JSON responce is : "+response);
if(!response.equals(""))
{
try {
JSONObject jso = new JSONObject(response);
int UName = jso.getInt("status1");
if(UName==1)
{
String status = jso.getString("status");
ret=status.substring(13,status.length()-2);
todoItems.add(0, status);
aa.notifyDataSetChanged();
}
else if(UName==-1)
{
String status = jso.getString("status");
//display(status);
Intent intObj=new Intent(pdf.this,Webview.class);
intObj.putExtra("USERNAME", status);
startActivity(intObj);
}
else
{
// int count=Integer.parseInt(UName);
// display("Number of Projects have been handling in AFL right now: "+count);
list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("reps1");
for(int i=0;i<array.length();i++)
{
list1.add(array.getJSONObject(i).getString("pdfName"));
}
itr=list1.iterator();
while(itr.hasNext())
{
//str1=itr.next()+"\n";
todoItems.add(0, itr.next().toString());
aa.notifyDataSetChanged();
}
//tv1.setText(str1);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return;
}
}
else
{
display("unable to reach the server");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent intObj=new Intent(pdf.this, MainActivity.class);
intObj.putExtra("finish", true); // if you are checking for this in your other Activities
intObj.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intObj);
//pdf.this.finish();
finish();
return (true);
}
return super.onOptionsItemSelected(item);
}
}
package com.example.nasadailyimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class NasaDailyImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nasa_daily_image);
IotdHandler handler = new IotdHandler();
System.out.println("handler object created");
Log.d("NasaDailyImage","handler object created");
new ConfigParser().execute();//here i have called execute on my AsyncTaskclass
// handler.processFeed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nasa_daily_image, menu);
return true;
}
}
and my ConfigParser class
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.AsyncTask;
import android.util.Log;
public class ConfigParser extends AsyncTask<Void, Void,Void > {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
IotdHandler handler=new IotdHandler();
reader.setContentHandler(handler);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
Log.d("IotdHandler", "Exception");
e.printStackTrace();
}
return null;
}
}
and my IotdHandler Class
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
private String imageUrl;
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{ ioe.printStackTrace(); }
return null;
}
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (localName.equals("enclosure"))
{ inUrl = true;
imageUrl=attributes.getValue("url");
System.out.println(imageUrl);
}
else { inUrl = false; }
if (localName.startsWith("item"))
{ inItem = true; }
else if (inItem) {
if (localName.equals("title"))
{ inTitle = true;
System.out.println("invtitle");}
else { inTitle = false; }
if (localName.equals("description"))
{ inDescription = true;
System.out.println("indiscription");}
else { inDescription = false; }
if (localName.equals("pubDate"))
{ inDate = true;
System.out.println("dtae");}
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(imageUrl); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
So basically I want to get daily image updates from NASA, but in my program everything is returning null I don't know what I am trying wrong, my xml file is not parsing to avoid the NetworkOnMainTHread I have also used Async class, any help.
Here is the code parsing xml rss feed...
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity {
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> pubDate;
ItemAdapter adapter1;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ListView list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
pubDate = new ArrayList<String>();
parse();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
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("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("description");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
description.add(((Node) websiteList.item(0)).getNodeValue());
NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
pubDate.add(((Node) websiteList1.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView date_text;
}
public ItemAdapter(Context context) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.date_text = (TextView) view.findViewById(R.id.date_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+Html.fromHtml(description.get(position)));
holder.date_text.setText(""+pubDate.get(position));
return view;
}
}
}
I posted a Gist on how to do this using the android-rss library with the droidQuery library:
final RSSHandler handler = new RSSHandler(new RSSConfig());
$.ajax(new AjaxOptions().url(options.url())
.type("GET")
.dataType("XML")
.context(this)
.SAXContentHandler(handler)
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
RSSFeed feed = handler.feed();
//TODO: handle feed here.
}
}));
Make an interface in your project first
public interface mMyInterface {
void processFinish(String response);
}
Then in your AsyncTaskClass do the following modifications
public class ConfigParser extends AsyncTask<Void, Void,Void > {
public mMyInterface delegate=null;
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
//Log.i("inJSONPARSERCLASS","success");
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpResponse httpResponse=client.execute(post);
HttpEntity entity=httpResponse.getEntity();
is=entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.e("Connection Error", "Error " + e.toString());
}
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();
xml=sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("main XML",""+xml);
return xml;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
delegate.processFinish(result);
}
}
Now in your class which is extending the activity , implement the interface mMyInterface , this will override its method processFinish(String response), now use "response" as a string and pass it to the class where the parsing is being done
#Override
public void processFinish(String response) {
String xml=response;
//do SAXparsing stuff here, parse this xml string which contains the whole data u need to
parse
}
I hope this hint will work out for you very well. :)