Thursday 27 December 2012

Android WebService With AsyncTask,Saxparser,HttpClient in Custom ListView


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 


AndroidPeople
www.androidpeople.com


iPhoneAppDeveloper
www.iphone-app-developer.com

 


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 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();
         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 getChannelList() {
        return channelList;
    }
    public void setChannelList(List 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 xmlParse() throws IOException 
        {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            List 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 executeRequest( ) throws ClientProtocolException, IOException
{
           
        
        //AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        HttpClient client = new DefaultHttpClient();

        String response= "";            
    ArrayList resarrHotelList= null;
    ArrayList params = new ArrayList();
    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) fdParser.xmlParse();  
             instream.close();
         }
                                  
    if(resarrHotelList!=null)
     Log.i("INFOOOO++++", "LIST"+resarrHotelList.size());
    //client.close();
    return resarrHotelList;
  
}  
}


ListAdapter.java

public class ListAdapter extends ArrayAdapter {
    //mapData is an hashmap of hotelId vs arraylist, 
    private ArrayList reservationdata;
    private Context ctx;
    public ListAdapter(Context context, int textViewResourceId,
            ArrayList 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 Content = new ArrayList();

    /** 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>{ 
        
        //  private String Content;  

        ArrayList 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 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 content) {
            Dialog.dismiss();

            if (Error != null) {
                Toast.makeText(ctx, "Pls Try Again  " + Error,
                        Toast.LENGTH_LONG).show();
            } 
            else {
                updateView(content);
                
                
            }
        }
    }
    private void updateView(ArrayList content) {

        this.Content.clear();

        this.Content.addAll(content);

        this.htlAdapt.notifyDataSetChanged();
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    
}


No comments:

Post a Comment

Free Automatic Backlink