0

I am downloading the zip file from my android app. Activity is getting stopped when click on Download button. the following is the code for downloading the zip file.

Download Code:

public void myDownload(View v) {


            URL url;
            try {
                url = new URL("https://github.com/jquery/jquery/archive/master.zip");
                try {
                    InputStream in = url.openStream();
                    FileOutputStream fos = new FileOutputStream(new File("Master.zip"));
                    System.out.println("Reading the file.");
                    int length = -1;
                    byte[] buffer = new byte[1024];// buffer for portion of data from
                    // connection
                    while ((length = in.read(buffer)) > -1) {
                        fos.write(buffer, 0, length);
                    }
                    fos.close();
                    in.close();
                    System.out.println("File Downloaded");

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

}

Thanks for any help!

usd123
  • 37
  • 1
  • 8

2 Answers2

0

@usd123 : Are you getting some sort of exception. As per your code things seems fine. Only problem I can guess you might connecting to specific URL on Main UI Thread which leads to ANR(Activity Not Responding). As per Android documentation network read/write task should not be performed on Main UI thread. They either needs to be done via Async Task or via a service. Please read http://developer.android.com/reference/android/os/StrictMode.html Hope this helps!

theJango
  • 1,100
  • 10
  • 22
0

You should not call internet/network calls in main thread. Try AsyncTask to run it off the main thread and update UI with Handlers.

Aswin
  • 1,154
  • 1
  • 11
  • 29