Thursday, December 4, 2014

Android Zip Unzip a Folder Demo | Unzip to a zip file in Android | Code for unzip a file in android

Hello Friends,

Today I am going to share code for unzip a file into android phone sd-card. For that I am using File chooser to select a zip file then using ZipInputStream I convert it into unzip file.

Reference- https://github.com/iPaulPro/aFileChooser


Below is the source code, you can download zip code too from below download link-

1)MainActivity.java-

package com.manish.androidhub4you.zip.unzip;

import java.io.File;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.ipaulpro.afilechooser.utils.FileUtils;

public class MainActivity extends Activity implements OnClickListener{

       private static final int PICKFILE_RESULT_CODE = 0;
       private String mFilePath;
       private Button mButtonChoose;
       private  String mDestinationFile =CommonMethod.unzipDestination.toString()+"/";

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              mButtonChoose=(Button)findViewById(R.id.button_choose);
             
              mButtonChoose.setOnClickListener(this);
             
       }
      
       @Override
       public void onClick(View v) {
              // TODO Auto-generated method stub
              switch(v.getId()){
              case R.id.button_choose:
                     mShowChooser();
                     break;
                    
              }
             
       }
      
      
       /*
        * (non-Javadoc)
        * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
        */
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              super.onActivityResult(requestCode, resultCode, data);

              if (resultCode != RESULT_OK) {

                     return;
              }
              switch (requestCode) {
             
              case PICKFILE_RESULT_CODE:
                     // If the file selection was successful
                     if (resultCode == RESULT_OK) {
                           if (data != null) {
                                  // Get the URI of the selected file
                                  final Uri uri = data.getData();

                                  try {
                                         // Create a file instance from the URI
                                         final File file = FileUtils.getFile(uri);
                                         mFilePath = file.getAbsolutePath();

                                         if (uri != null) {
                                                 if(CommonMethod.unzipDestination.exists()==false) {
                                                        CommonMethod.unzipDestination.mkdirs();
                                             }
                                                Toast.makeText(MainActivity.this,"File Selected: " + mFilePath,Toast.LENGTH_LONG).show();
                                                 CommonMethod.mUnpackZipFile(mFilePath,mDestinationFile);
                                         }
                                        
                                        
                                  } catch (Exception e) {
                                         Log.e("FileSelectorTestActivity", "File select error",e);
                                  }
                           }
                     }
                     break;
              }
}
      
       /**
        * method for open a chooser to choose zip file
        */
       private void mShowChooser() {
              // Use the GET_CONTENT intent from the utility class
              Intent target = FileUtils.createGetContentIntent();
              // Create the chooser Intent
              Intent intent = Intent.createChooser(target,
                           getString(R.string.choose_file));
              try {
                     startActivityForResult(intent, PICKFILE_RESULT_CODE);
              } catch (ActivityNotFoundException e) {
                     // The reason for the existence of aFileChooser
              }

  }

      
}

2)CommonMethod.java-


package com.manish.androidhub4you.zip.unzip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
 *
 * @author manish
 *
 */
public class CommonMethod {
      
       public static File root = android.os.Environment.getExternalStorageDirectory();

       public static File unzipDestination = new File(root.getAbsolutePath() + "/Androidhub4you/UNZIP");
      
/**
 *
 * @param mArchivePath
 * @param mZipname
 * @param mOutPutStream
 * @return
 */
        public static boolean mUnpackZipFile(String mArchivePath,String mOutPutStream) { 
                InputStream inputstream; 
                ZipInputStream zipinputstream; 
                try
                 String filename; 
                 inputstream = new FileInputStream(mArchivePath); 
                 zipinputstream = new ZipInputStream(new BufferedInputStream(inputstream)); 
                 ZipEntry mZipEntry; 
                 byte[] buffer = new byte[1024]; 
                 int count; 
               
                 while ((mZipEntry = zipinputstream.getNextEntry()) != null) { 
                  filename = mZipEntry.getName(); 
               
                  if (mZipEntry.isDirectory()) { 
                   File fmd = new File(mOutPutStream + filename); 
                   fmd.mkdirs(); 
                   continue
                  } 
               
                  FileOutputStream fileoutputstream = new FileOutputStream(mOutPutStream + filename); 
               
                  while ((count = zipinputstream.read(buffer)) != -1) { 
                   fileoutputstream.write(buffer, 0, count); 
                  } 
                 
                
                  fileoutputstream.close(); 
                  zipinputstream.closeEntry(); 
                 } 
               
                 zipinputstream.close(); 
                } catch (IOException e) { 
                 e.printStackTrace(); 
                 return false
                } 
               
                return true
               } 
               

}

3)activity_main.xml-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_choose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="44dp"
        android:text="Choose file to unzip" />

</RelativeLayout>

3)manifest.xml-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.androidhub4you.zip.unzip"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
   
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
       <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.androidhub4you.zip.unzip.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <activity
            android:name="com.ipaulpro.afilechooser.FileChooserActivity"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.GET_CONTENT" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.OPENABLE" />

                <data android:mimeType="*/*" />
            </intent-filter>
        </activity>
       
    </application>

</manifest>


DOWNLOAD-ZIP-CODE

Thanks,
Manish

10 comments :

  1. Hello Sir.. This is a very good tutorial and very helpful.
    But the problem is that if i execute this code on more than one .zip file than whole unzip file is getting mix up with one another. There was no proper formation maintained with unzip format. So,how can i over come this problem??

    Hope u understand what i am trying to say?

    ReplyDelete
    Replies
    1. you can create a dynamic folder for your destination files.

      Delete
    2. My image in SQLIte how to get the image in circle in adapter

      Delete
    3. Try below link-
      http://www.androidhub4you.com/2014/10/android-custom-shape-imageview-rounded.html

      Delete
  2. sir if password protected zip file

    ReplyDelete
  3. sir if password protected zip file

    ReplyDelete
    Replies
    1. No idea brother, I think it should give some exception. Run the code and debug and update me too if you find any solution for this.

      Thanks you!

      Delete
  4. 05-27 11:53:59.431: E/Decompress(14620): java.io.FileNotFoundException: /storage/sdcard0/HYS_Module/0721011004_2_2014HYS_Module/0721011004_2_2014/tbl_HYS_HH_Member_upd.xml: open failed: ENOENT (No such file or directory)
    05-27 11:53:59.431: E/Decompress(14620): at libcore.io.IoBridge.open(IoBridge.java:460)





    its show the errr

    ReplyDelete
  5. in my zip file there has 4 xml file

    ReplyDelete

Note: Only a member of this blog may post a comment.