2

Hello I have manage to download a file. And now I am using the class from

http://www.jondev.net/articles/Unzipping_Files_with_Android_%28Programmatically%29

So, I would like an advice as to where should I implement this class. And also is there any way to delete the zip file after the decompression? Thank you.

This is my main code

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.xml);
 btn_src = (Button) findViewById(R.id.source);

    btn_src.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            String link;
            link = resurl + "9_1342080926-1.0.zip";

            downloadRes = new downloadRes();
            downloadRes.execute(link);          
        }

        });

    String zipFile = Environment.getExternalStorageDirectory() + 
"/aiyo/aiyomag/edition/9_1342080926-1.0.zip"; 
    String unzipLocation = Environment.getExternalStorageDirectory() + 
"/aiyo/aiyomag/edition/sourcetest"; 

    Decompress d = new Decompress(zipFile, unzipLocation); 
    d.unzip(); 

Is that the right way for me to implement the unzipping process?

I am really new in android. Any kind of help would be appreciated.

EDIT - UNZIP IN ASYNCTASK

public class downloadRes extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... params) {




        try {


            File root = android.os.Environment
                    .getExternalStorageDirectory();
            File dir = new File(root.getAbsolutePath() + "/aiyo/aiyomag/edition/sourcetest");

            if (dir.exists() == false) {
                dir.mkdirs();
            }

            Log.d("param", params[0]);
            URL url = new URL(params[0]); // you can write here any link
            URLConnection connection = url.openConnection();
            connection.connect();



            // get file name and file extension


            String fileExtenstion = MimeTypeMap
                    .getFileExtensionFromUrl(params[0]);
            String name = URLUtil.guessFileName(params[0], null,
                    fileExtenstion);
            File file = new File(dir, name);
            Log.d("File in content","The file is "+file.getName());

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            OutputStream fos = new FileOutputStream(file);

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

            int lenghtOfFile = connection.getContentLength();
            int total = 0;
            byte baf[] = new byte[1024];
            int current = 0;
            while ((current = bis.read(baf)) != -1) {

                total += current;
                // publishProgress("" + (int) ((total * 100) /
                // lenghtOfFile));
                mProgressDialog.setProgress(((total * 100) / lenghtOfFile));
                fos.write(baf, 0, current);
            }

            // close every file stream
            fos.flush();
            fos.close();
            is.close();

        } catch (IOException e) {
            Log.e("DownloadManager", "Error: " + e);
        }
       return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        mProgressDialog.setProgress(Integer.parseInt(values[0]));
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
      //  if (fileInteger == max) {
      //      dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
      //      return;
      //  }


        Log.d("post execute", "i::" + fileInteger);
      //  fileInteger++;
        // publishProgress("" + (int) ((fileInteger * 100) / max));
    //    mProgressDialog.setSecondaryProgress(((fileInteger * 100) / max));
        String link = resurl+"9_1342080926-1.0.zip";

        downloadRes = new downloadRes();
        downloadRes.execute(link);
    }

}

That is just the class however. And I still call it in the onCreate.

akemalFirdaus
  • 606
  • 1
  • 7
  • 15
  • This doesn't answer your question, but here are some best practices: 1) Move your `close()` calls to a `finally` block. Otherwise, if an exception happens and you go to the `catch` block, the resources won't be closed. 2) Consider using [`Context.getExternalFilesDir()`](http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)) instead of building the path yourself. 3) Do all the long-running operations in the `AsyncTask` (download and decompress both). – quietmint Oct 05 '12 at 01:35
  • @user113215 How do I set the download to be on onClickListener if I put them inside of the asyncTask class? – akemalFirdaus Oct 05 '12 at 01:42
  • @akemalFirdaus, call the `execute` method of your `AsyncTask` class. – mrres1 Oct 05 '12 at 01:54

2 Answers2

2

Some psuedo code to re-iterate what's been answered:

onCreate()
{
    buttonOnClick
    {
        DownloadAndUnzip.execute(the url)
    }
}

inner class DownloadAndUnzip()
{
    boolean failed;

    preExecute()
    {
        failed = false;
    }

    doInBackground()
    {
        try
        {
            start download stream
        }
        catch
        {
            failed = true
        }
        finally
        {
            close streams
        }

        if failed == false
        {
            try
            {
                decompress(zip file)
            }
            catch
            {
                failed = true
            }
            finally
            {
                close streams
            }
        }
    }

    postExecute()
    {
        if failed
        {
            download failed

            notify user
        }
        else
        {
            download and unzip is good

            zip.delete
        }
    }
}
mrres1
  • 1,147
  • 6
  • 10
1

I suggest that you execute the download and decompression in an AsyncTask. This is a good practice and avoids freezing your Activity or GUI when the process takes a while. Starting from ICS (or earlier maybe) you can not execute webrequests in your Activity code and an Async approach gets mandatory. If you don't, the webrequest or download will fail.

EDIT : This might be useful link tutorial.

Community
  • 1
  • 1
Segers-Ian
  • 1,027
  • 10
  • 21
  • So you mean that its not suitable to put the decompression class right after the download? – akemalFirdaus Oct 04 '12 at 12:08
  • What I meant, run the download and decompression in an AsyncTask because both might take some time to execute (i.e. file is too big, slow connection). Your next method only runs when the previous method ends in an synchronized context. This means, if you hit the button, you're GUI will not respond till the file is downloaded AND decompressed. If you run download and decompress in an Async task, your GUI keeps running while download is going on. The user can do other actions in the mean time. If I where you I would run actually Download and Decompress in two separate AsyncTasks. – Segers-Ian Oct 04 '12 at 13:40
  • @akemalFirdaus, You should do some reading on Java Threads and Multi-threaded applications. The reason Ian is suggesting to do both, the download and the unzip, in the `AsyncTask` is because it is a seperate thread (not the same one the UI is running on). Running an un-zip or even the download on the UI thread will stop your UI. The user won't be able to click anything. – mrres1 Oct 05 '12 at 01:57
  • @mrres1 Yes I am aware of that. But for now I just want to accomplish unzipping these files :( any ideas? – akemalFirdaus Oct 05 '12 at 02:06