Can someone help me with some file download code
<p>Hi I am making a app that fetches a xml file and displays the results with a button labeled get it. I need help with when the button is clicked it will take the .pkg file url in the xml file and download it with some sort of progress reporting. Any help would be awesome thanks in advance. Here is what I have so far it has a error in the download code I tried maybe someone can fix this for me. I am stumped also the links are to .pkg files </p>

<p>package com.mypackagename;</p>

<p>import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;</p>

<p>import java.io.BufferedInputStream;</p>

<p>import java.io.File;</p>

<p>import java.io.FileOutputStream;</p>

<p>import java.io.IOException;</p>

<p>import java.io.InputStream;</p>

<p>import java.net.URL;</p>

<p>import java.net.URLConnection;</p>

<p>import org.apache.http.util.ByteArrayBuffer;</p>

<p>import android.util.Log;</p>

<p>public class MainActivity extends ListActivity {
    String XML_URL = "http://www.mysite.com/book.xml";
    private DocumentBuilder docBuilder;
    private Document doc;
    private DocumentBuilderFactory docBuilderFactory;
    private String bookImageUrl;
    private int nodeListbooksLength;
    private String bookId;
    private String bookUrl;
    private String bookDescription;
    private String bookTitle;</p>

<pre><code>ButtonListMenuAdapter notes;
ArrayList&lt;Book&gt; list;
TextView tv_title;
ImageView iv_logo;
private String Title;
  Drawable booksImagesList[];


/** Called when the activity is first created. 1 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv_title = (TextView) findViewById(R.id.TextView01);
    iv_logo = (ImageView) findViewById(R.id.ImageView01);
    list = new ArrayList&lt;Book&gt;();
    parseXML();
    notes = new ButtonListMenuAdapter( 
            this, 
            R.layout.book_row,
            list );
    setListAdapter( notes );
}
private void parseXML()
{
    try{
        Log.d("MainActivity", "Connecting Server");
        InputStream inStream =openHttpConnection(XML_URL);
        Log.d("MainActivity", "Fetching Data Completed");
        if(inStream!=null){
            docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setCoalescing(true);
            docBuilder = docBuilderFactory.newDocumentBuilder();
            docBuilder.isValidating();
            doc = docBuilder.parse(inStream);


            NodeList nodeListbookTitle = doc.getDocumentElement().getElementsByTagName("Title1");
            if(nodeListbookTitle.getLength()&gt;0){
                Element elementbooktitile = (Element) nodeListbookTitle.item(0);
                NodeList nodeListElementbooktitle = elementbooktitile.getChildNodes();
                if(nodeListElementbooktitle.getLength()&gt;0)
                {
                    Title = ((Node) nodeListElementbooktitle.item(0)).getNodeValue();
                    Log.d("MainActivity", "Title:"+Title);
                    tv_title.setText(Title);
                }
            }

            NodeList nodeListbookBanner = doc.getDocumentElement().getElementsByTagName("logo");
            if(nodeListbookBanner.getLength()&gt;0){
                Element elementTeamBanner = (Element) nodeListbookBanner.item(0);
                NodeList nodeListElementTeamBanner = elementTeamBanner.getChildNodes();
                if(nodeListElementTeamBanner.getLength()&gt;0)
                {
                    bookImageUrl = ((Node) nodeListElementTeamBanner.item(0)).getNodeValue();
                    try {
                        DownloadFilesTask d = new DownloadFilesTask();
                        d.execute(new URL(bookImageUrl));
                        d.sendObjectImageView(iv_logo);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Log.d("ERROR getView", "EX::"+e);
                    }

                    Log.d("MainActivity", "bookImageUrl:"+bookImageUrl);
                    Log.d("MainActivity", "");
                }
            }
            NodeList nodeListbook = doc.getDocumentElement().getElementsByTagName("Book");
            Log.d("MainActivity","nodeListbook Length--"+nodeListbook.getLength());
            nodeListbooksLength=nodeListbook.getLength();

            booksImagesList = new Drawable[nodeListbooksLength+1];

            if(nodeListbooksLength&gt;0){
                for(int v=0;v&lt;nodeListbooksLength;v++){
                    Node nodebook = nodeListbook.item(v);

                    if (nodebook.getNodeType() == Node.ELEMENT_NODE){
                        Element elementbookResult = (Element) nodebook;
                        bookId=elementbookResult.getAttribute("bid");
                        Log.d("MainActivity","----in bookId- -&gt;"+v+"   "+bookId);

                        bookImageUrl=elementbookResult.getAttribute("bimg");
                        Log.d("MainActivity","--bookImageUrl---&gt;"+bookImageUrl);
                        bookTitle=elementbookResult.getAttribute("bte");
                        Log.d("MainActivity","--bookTitle---&gt;"+bookTitle);
                        bookDescription=elementbookResult.getAttribute("bsd");
                        Log.d("MainActivity","--bookDescription---&gt;"+bookDescription);
                        bookUrl=elementbookResult.getAttribute("bph");
                        Log.d("MainActivity","--bookUrl:---&gt;"+bookUrl);
                        list.add( new Book( bookId, bookImageUrl,bookTitle,bookDescription,bookUrl) );
                    }
                }
            }


        }
    }catch(Exception e){
        Log.d("MainActivity", "parseXML:"+e);
    }
}
private InputStream openHttpConnection(String urlStr) {
    InputStream in = null;
    int resCode = -1;

    try {
        Log.d("openHttpConnection", "URL:"+urlStr);
        URL url = new URL(urlStr);
        URLConnection urlConn = url.openConnection();

        if (!(urlConn instanceof HttpURLConnection)) {
            throw new IOException ("URL is not an Http URL");
        }
        Log.d("openHttpConnection", "httpConn:1");
        HttpURLConnection httpConn = (HttpURLConnection)urlConn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        Log.d("openHttpConnection", "setting requests and properties");
        httpConn.connect(); 
        Log.d("openHttpConnection", "Connected successfully");

        resCode = httpConn.getResponseCode();    

        Log.d("openHttpConnection", "resCode"+resCode);
        if (resCode == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream(); 
            Log.d("openHttpConnection", "Fetchinf data done");
        }         
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.d("openHttpConnection", "1"+e);
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("openHttpConnection", ""+e);
    }
    return in;
}

private HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse response;
private HttpContext localContext;
private String ret;

private InputStream postPage(String url, String data) {
    InputStream is = null;
    ret = null;

    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

    httpPost = new HttpPost(url);
    response = null;

    StringEntity tmp = null;        

    httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
        "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
    httpPost.setHeader("Accept", "text/html,application/xml," +
        "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        tmp = new StringEntity(data,"UTF-8");
    } catch (UnsupportedEncodingException e) {
        System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
    }

    httpPost.setEntity(tmp);

    try {
        response = httpClient.execute(httpPost,localContext);
    } catch (ClientProtocolException e) {
        System.out.println("HTTPHelp : ClientProtocolException : "+e);
    } catch (IOException e) {
        System.out.println("HTTPHelp : IOException : "+e);
    } 
            ret = response.getStatusLine().toString();
            HttpEntity he = response.getEntity();
            try {
                InputStream inStream = he.getContent();
                is = inStream;
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return is;
    }

class Book
{
    public String getBookId() {
        return bookId;
    }
    public String getBookImageUrl() {
        return bookImageUrl;
    }
    public String getBookTitle() {
        return bookTitle;
    }
    public String getBookDescription() {
        return bookDescription;
    }
    public String getBookUrl() {
        return bookUrl;
    }
    private String bookId;
    private String bookImageUrl;
    private String bookTitle;
    private String bookDescription;
    private String bookUrl;
    public Book(String bookId, String bookImageUrl, String bookTitle,String bookDescription, String bookUrl) {
        this.bookId = bookId;
        this.bookImageUrl = bookImageUrl;
        this.bookTitle = bookTitle;
        this.bookDescription = bookDescription;
        this.bookUrl = bookUrl;
    }


}

public class ButtonListMenuAdapter extends BaseAdapter {

    public static final String LOG_TAG = "ButtonListAdapter";

    private Context context;
    private List&lt;Book&gt; menuList;
    private int rowResID;



    public ButtonListMenuAdapter(MainActivity context, int rowResID,
            ArrayList&lt;Book&gt; menuList) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.rowResID = rowResID;
        this.menuList = menuList;
    }

    public int getCount() {                        
        return menuList.size();
    }

    public Object getItem(int position) {     
        return menuList.get(position);
    }

    public long getItemId(int position) {  
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) { 
        final Book row = menuList.get(position);
        LayoutInflater inflater = LayoutInflater.from( context );
        View v = inflater.inflate(  rowResID, parent, false );
        TextView tv_title = (TextView)v.findViewById(R.id.Text_book_title);
        tv_title.setText(row.getBookTitle());
        TextView tv_desc = (TextView)v.findViewById(R.id.Text_Book_Desc);
        tv_desc.setText(row.getBookDescription());
        ImageView iv_book_img = (ImageView)v.findViewById(R.id.Image_book);
        if(booksImagesList[position]==null)
        {
            try {
                DownloadFilesTask d = new DownloadFilesTask();
                d.execute(new URL(row.getBookImageUrl()));
                d.sendObjectImageView(iv_book_img,position);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("ERROR getView", "EX::"+e);
            }
        }
        else
        {
            iv_book_img.setImageDrawable(booksImagesList[position]);
            Log.d("Not","Reloaded");
        }

        Button b_get_book = (Button)v.findViewById(R.id.Button01);
        b_get_book.setOnClickListener(
                new View.OnClickListener()
                {              
                    public void onClick(View v) {




                                private final String PATH = "/mnt/sdcard/";  //put the downloaded file here





                                public void DownloadFromUrl(String bookUrl, String fileName) {  //this is the downloader method

                                        try {

                                                URL url = new URL("http://mysite.com/" + bookUrl); //you can write here any link

                                                File file = new File(fileName);



                                                long startTime = System.currentTimeMillis();

                                                Log.d("ImageManager", "download begining");

                                                Log.d("ImageManager", "download url:" + url);

                                                Log.d("ImageManager", "downloaded file name:" + fileName);

                                                /* Open a connection to that URL. */

                                                URLConnection ucon = url.openConnection();



                                                /*

                                                 * Define InputStreams to read from the URLConnection.

                                                 */

                                                InputStream is = ucon.getInputStream();

                                                BufferedInputStream bis = new BufferedInputStream(is);



                                                /*

                                                 * Read bytes to the Buffer until there is nothing more to read(-1).

                                                 */

                                                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                                                int current = 0;

                                                while ((current = bis.read()) != -1) {

                                                        baf.append((byte) current);

                                                }



                                                /* Convert the Bytes read to a String. */

                                                FileOutputStream fos = new FileOutputStream(PATH+file);

                                                fos.write(baf.toByteArray());

                                                fos.close();

                                                Log.d("ImageManager", "download ready in"

                                                                + ((System.currentTimeMillis() - startTime) / 1000)

                                                                + " sec");



                                        } catch (IOException e) {

                                                Log.d("ImageManager", "Error: " + e);

                                        }



                                }


                    }
           });
        return v;
    }
}

private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
    ImageView iv;
    int id;
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;

        downloadDrawable(urls[0].toString());

        return totalSize;
    }

    public void sendObjectImageView(ImageView ivLogo) {
        // TODO Auto-generated method stub
        this.iv = ivLogo;
        id = -1;
    }

    public void sendObjectImageView(ImageView iv,int id) {
        // TODO Auto-generated method stub
        this.iv = iv;
        this.id = id;
    }

    protected void onProgressUpdate(Integer... progress) {
        Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);
    }
    protected void onPostExecute(Long result) {
        Log.d("DownloadFilesTask", "onPostExecute"+result);
        if(d!=null &amp;&amp; iv!=null)
        {
            iv.setImageDrawable(d);
            if(id!=-1)
            booksImagesList[id] = d;
        }
    }

    private Drawable d;
    public Drawable downloadDrawable(String imageUrl) {


        try {
            Log.d("downloadDrawable", "Starting Connection");
            URL url = new URL(imageUrl);
            URLConnection conn = url.openConnection();
            conn.connect();
            Log.d("downloadDrawable", "Connection Created Successfully");
            InputStream is = conn.getInputStream();
            Log.d("downloadDrawable", "InputStream created Successfully");
            d = Drawable.createFromStream(is, url.toString());
            Log.d("downloadDrawable", "Drawable created Successfully");
            is.close();

        } catch (IOException e) {
           Log.d("ERROR3", "Ex::"+e);

        }

         return d;
    }

}
</code></pre>

<p>}</p>
