Android WebService With AsyncTask,Saxparser,HttpClient in Custom ListView
DOWNLOAD SOURCE CODE
android webservice with AsyncTask,saxparser and httpclient.with listview
we are going to how to access xml file with saxparser using web service.
This is XML format getting all the data. thriught given URL
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
http://str10.aceonetest.com/myxml.xml
in this url only example XML file is there. i am accessing this url only for parsing.
ItemStructure.java
public class ItemStructure {
private String name;
private String website;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
XMLhandler.java
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLhandler extends DefaultHandler {
//private ChannelList channelList = new ChannelList();
private StringBuilder builder;
private List<ItemStructure> channelList;
private ItemStructure chList;
// private RoomRate currentMessage=new RoomRate();
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
builder.append(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, name);
if (chList != null){
if (localName.equalsIgnoreCase("name"))
{
chList.setName(builder.toString());
Log.i("111CITYYYYYYY", "++++++++"+chList.getName());
}
else if (localName.equalsIgnoreCase("website")){
chList.setWebsite(builder.toString());
}
else if (localName.equalsIgnoreCase("item")){
channelList.add(chList);
}
builder.setLength(0);
}
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
channelList = new ArrayList<ItemStructure>();
builder = new StringBuilder();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase("item")){
this.chList = new ItemStructure();
builder.setLength(0);
}
}
public List<ItemStructure> getChannelList() {
return channelList;
}
public void setChannelList(List<ItemStructure> channelList) {
this.channelList = channelList;
}
}
XMLparsing.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class XMLparsing {
private InputStream xmlInputStream;
public XMLparsing(InputStream xmlInputStream){
this.xmlInputStream = xmlInputStream;
}
public List<ItemStructure> xmlParse() throws IOException
{
SAXParserFactory factory = SAXParserFactory.newInstance();
List<ItemStructure> channellist=null;
try {
SAXParser parser = factory.newSAXParser();
XMLhandler handler = new XMLhandler();
parser.parse(this.getInputStream(),handler);
return handler.getChannelList();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return channellist;
}
private InputStream getInputStream() {
// TODO Auto-generated method stub
return xmlInputStream;
}
}
URLHelper.java
public class URLHelper {
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
public static ArrayList<ItemStructure> executeRequest( ) throws ClientProtocolException, IOException
{
//AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
HttpClient client = new DefaultHttpClient();
String response= "";
ArrayList<ItemStructure> resarrHotelList= null;
ArrayList <NameValuePair> params = new ArrayList<NameValuePair>();
String url1 = "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml";
HttpGet getUrl = new HttpGet(url1);
HttpResponse httpResponse = client.execute(getUrl);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
XMLparsing fdParser = new XMLparsing(instream);
resarrHotelList = (ArrayList<ItemStructure>) fdParser.xmlParse();
instream.close();
}
if(resarrHotelList!=null)
Log.i("INFOOOO++++", "LIST"+resarrHotelList.size());
//client.close();
return resarrHotelList;
}
}
ListAdapter.java
public class ListAdapter extends ArrayAdapter<ItemStructure> {
//mapData is an hashmap of hotelId vs arraylist,
private ArrayList<ItemStructure> reservationdata;
private Context ctx;
public ListAdapter(Context context, int textViewResourceId,
ArrayList<ItemStructure> reservationdata) {
super(context, textViewResourceId, reservationdata);
this.reservationdata = reservationdata;
this.ctx = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.main, null);
//v = vi.inflate(R.layout.bookingdetails, null);
}
final ItemStructure o = reservationdata.get(position);
if (o != null) {
TextView studentName = (TextView) v.findViewById(R.id.TextView01);
TextView conNo = (TextView) v.findViewById(R.id.TextView02);
studentName.setText(o.getName());
conNo.setText(o.getWebsite());
//fatherName.setText(o.getFatherName());
Log.i("INFOOOOOOO", "DISPLAY NAME"+o.getName());
}
return v;
}
}
MainActivity.java
public class MainActivity extends Activity {
private Object TestAsyncTask;
private ListAdapter htlAdapt = null;
private ListView htlListView = null;
private String name;
private ItemStructure reservationdata=new ItemStructure();
static ArrayList<ItemStructure> Content = new ArrayList<ItemStructure>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
setContentView(R.layout.listview);
// TextView hotelname=(TextView)findViewById(R.id.slist);
htlListView = (ListView) findViewById(R.id.ListView01);
htlAdapt = new ListAdapter(this, R.layout.main,
Content);
htlListView.setAdapter(htlAdapt);
getURL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
}
public void getURL(String url) {
TestAsyncTask test = new TestAsyncTask();
test.setContext(this);
test.execute(url);
}
class TestAsyncTask extends
AsyncTask<String, Void, ArrayList<ItemStructure>>{
// private String Content;
ArrayList<ItemStructure> Contents = null;
private String Error = null;
private ProgressDialog Dialog;
private Context ctx;
public void setContext(Context ctx) {
this.ctx = ctx;
}
protected void onPreExecute() {
Dialog = new ProgressDialog(ctx);
Dialog.setMessage("Loading Data...");
Dialog.show();
}
protected ArrayList<ItemStructure> doInBackground(String... urls) {
try {
Log.i("INFOOOOOO", "++++++++1");
Contents = URLHelper.executeRequest();
Log.i("INFOOOOOO", "++++++++"+Contents.size());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Contents;
}
protected void onPostExecute(ArrayList<ItemStructure> content) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(ctx, "Pls Try Again " + Error,
Toast.LENGTH_LONG).show();
}
else {
updateView(content);
}
}
}
private void updateView(ArrayList<ItemStructure> content) {
this.Content.clear();
this.Content.addAll(content);
this.htlAdapt.notifyDataSetChanged();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DOWNLOAD SOURCE CODE
android webservice with AsyncTask,saxparser and httpclient.with listview
we are going to how to access xml file with saxparser using web service.
This is XML format getting all the data. thriught given URL
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
http://str10.aceonetest.com/myxml.xml
in this url only example XML file is there. i am accessing this url only for parsing.
ItemStructure.java
public class ItemStructure {
private String name;
private String website;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
XMLhandler.java
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLhandler extends DefaultHandler {
//private ChannelList channelList = new ChannelList();
private StringBuilder builder;
private List<ItemStructure> channelList;
private ItemStructure chList;
// private RoomRate currentMessage=new RoomRate();
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
builder.append(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, name);
if (chList != null){
if (localName.equalsIgnoreCase("name"))
{
chList.setName(builder.toString());
Log.i("111CITYYYYYYY", "++++++++"+chList.getName());
}
else if (localName.equalsIgnoreCase("website")){
chList.setWebsite(builder.toString());
}
else if (localName.equalsIgnoreCase("item")){
channelList.add(chList);
}
builder.setLength(0);
}
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
channelList = new ArrayList<ItemStructure>();
builder = new StringBuilder();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase("item")){
this.chList = new ItemStructure();
builder.setLength(0);
}
}
public List<ItemStructure> getChannelList() {
return channelList;
}
public void setChannelList(List<ItemStructure> channelList) {
this.channelList = channelList;
}
}
XMLparsing.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class XMLparsing {
private InputStream xmlInputStream;
public XMLparsing(InputStream xmlInputStream){
this.xmlInputStream = xmlInputStream;
}
public List<ItemStructure> xmlParse() throws IOException
{
SAXParserFactory factory = SAXParserFactory.newInstance();
List<ItemStructure> channellist=null;
try {
SAXParser parser = factory.newSAXParser();
XMLhandler handler = new XMLhandler();
parser.parse(this.getInputStream(),handler);
return handler.getChannelList();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return channellist;
}
private InputStream getInputStream() {
// TODO Auto-generated method stub
return xmlInputStream;
}
}
URLHelper.java
public class URLHelper {
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
public static ArrayList<ItemStructure> executeRequest( ) throws ClientProtocolException, IOException
{
//AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
HttpClient client = new DefaultHttpClient();
String response= "";
ArrayList<ItemStructure> resarrHotelList= null;
ArrayList <NameValuePair> params = new ArrayList<NameValuePair>();
String url1 = "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml";
HttpGet getUrl = new HttpGet(url1);
HttpResponse httpResponse = client.execute(getUrl);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
XMLparsing fdParser = new XMLparsing(instream);
resarrHotelList = (ArrayList<ItemStructure>) fdParser.xmlParse();
instream.close();
}
if(resarrHotelList!=null)
Log.i("INFOOOO++++", "LIST"+resarrHotelList.size());
//client.close();
return resarrHotelList;
}
}
ListAdapter.java
public class ListAdapter extends ArrayAdapter<ItemStructure> {
//mapData is an hashmap of hotelId vs arraylist,
private ArrayList<ItemStructure> reservationdata;
private Context ctx;
public ListAdapter(Context context, int textViewResourceId,
ArrayList<ItemStructure> reservationdata) {
super(context, textViewResourceId, reservationdata);
this.reservationdata = reservationdata;
this.ctx = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.main, null);
//v = vi.inflate(R.layout.bookingdetails, null);
}
final ItemStructure o = reservationdata.get(position);
if (o != null) {
TextView studentName = (TextView) v.findViewById(R.id.TextView01);
TextView conNo = (TextView) v.findViewById(R.id.TextView02);
studentName.setText(o.getName());
conNo.setText(o.getWebsite());
//fatherName.setText(o.getFatherName());
Log.i("INFOOOOOOO", "DISPLAY NAME"+o.getName());
}
return v;
}
}
MainActivity.java
public class MainActivity extends Activity {
private Object TestAsyncTask;
private ListAdapter htlAdapt = null;
private ListView htlListView = null;
private String name;
private ItemStructure reservationdata=new ItemStructure();
static ArrayList<ItemStructure> Content = new ArrayList<ItemStructure>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
setContentView(R.layout.listview);
// TextView hotelname=(TextView)findViewById(R.id.slist);
htlListView = (ListView) findViewById(R.id.ListView01);
htlAdapt = new ListAdapter(this, R.layout.main,
Content);
htlListView.setAdapter(htlAdapt);
getURL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
}
public void getURL(String url) {
TestAsyncTask test = new TestAsyncTask();
test.setContext(this);
test.execute(url);
}
class TestAsyncTask extends
AsyncTask<String, Void, ArrayList<ItemStructure>>{
// private String Content;
ArrayList<ItemStructure> Contents = null;
private String Error = null;
private ProgressDialog Dialog;
private Context ctx;
public void setContext(Context ctx) {
this.ctx = ctx;
}
protected void onPreExecute() {
Dialog = new ProgressDialog(ctx);
Dialog.setMessage("Loading Data...");
Dialog.show();
}
protected ArrayList<ItemStructure> doInBackground(String... urls) {
try {
Log.i("INFOOOOOO", "++++++++1");
Contents = URLHelper.executeRequest();
Log.i("INFOOOOOO", "++++++++"+Contents.size());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Contents;
}
protected void onPostExecute(ArrayList<ItemStructure> content) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(ctx, "Pls Try Again " + Error,
Toast.LENGTH_LONG).show();
}
else {
updateView(content);
}
}
}
private void updateView(ArrayList<ItemStructure> content) {
this.Content.clear();
this.Content.addAll(content);
this.htlAdapt.notifyDataSetChanged();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
wonderful
ReplyDeletebut can u give me how to change listview with spinner with this exemple please
and iff u have example this my email montassar.zarroug@gmail.com
remove that listiew and add spinner then u can get data in spinner
ReplyDeleteThnx
msv
machi oru dought
ReplyDeleteGreat write up. One issue I have is that if the tags contain image links or html code (e.g. description tag of the xml for an rss feed), I just get back jumbled text. Any ideas how the parse such tags?
ReplyDeletehi vijay, nice article, but i have a doubt,I have 2 parameters emailID and password (fetch from EditText) and send it to webservice http URL which is based on PHP.and it will response (Success or failure) accordingly. on that response i have to call welcome or Againlogin page. also logout code too and if he has logged in it saves state till he doesnt logout...pls help me,its urgent,i am new to android. Thanks in adv.....
ReplyDeleteHi Ronak,
Deletebased on that response result you have to fix that issue. still u have doubt mean i'll give some sample codes.
Good stuff! Thanks a lot for writing this tut :)
ReplyDeleteawesome
ReplyDeleteThank you for the sample code could you please post the main.xml listview.xml and the manifest.xml...
ReplyDeleteafter the data is loaded i get a forseclose i think it has to do with my manifest
the link to the source code dont work megaupload has been banned unfortunately
thanks
please can you help me
ReplyDeletei heve a same project
but
i can't found a solution
i have a problem
can see with me please