26 Aug 2013

Unzipping Files with Android (Programmatically) | Extract zip file in android

This article is about how to write a utility class for extracting files and directories in a compressed zip archive, using built-in Java API.

The java.util.zip package provides the following classes for extracting files and directories from a ZIP archive:

ZipInputStream: this is the main class which can be used for reading zip file and extracting files and directories (entries) within the archive. Here are some important usages of this class:
-read a zip via its constructor ZipInputStream(FileInputStream)
-read entries of files and directories via method getNextEntry()
-read binary data of current entry via method read(byte)
-close current entry via method closeEntry()
-close the zip file via method close()

ZipEntry: this class represents an entry in the zip file. Each file or directory is represented as a ZipEntry object. Its method getName() returns a String which represents path of the file/directory. The path is in the following form:
folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext

Based on the path of a ZipEntry, we re-create directory structure when extracting the zip file.

Below class is used for unzip download zip and extract file and store your desire location.

import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipUtil
{
 private String zipFile;
 private String location;

 public UnzipUtil(String zipFile, String location)
 {
  this.zipFile = zipFile;
  this.location = location;

  dirChecker("");
 }

 public void unzip()
 {
  try
  {
   FileInputStream fin = new FileInputStream(zipFile);
   ZipInputStream zin = new ZipInputStream(fin);
   ZipEntry ze = null;
   while ((ze = zin.getNextEntry()) != null)
   {
    Log.v("Decompress", "Unzipping " + ze.getName());

    if(ze.isDirectory())
    {
     dirChecker(ze.getName());
    }
    else
    {
     FileOutputStream fout = new FileOutputStream(location + ze.getName());     

     byte[] buffer = new byte[8192];
     int len;
     while ((len = zin.read(buffer)) != -1)
     {
      fout.write(buffer, 0, len);
     }
     fout.close();

     zin.closeEntry();

    }

   }
   zin.close();
  }
  catch(Exception e)
  {
   Log.e("Decompress", "unzip", e);
  }

 }

 private void dirChecker(String dir)
 {
  File f = new File(location + dir);
  if(!f.isDirectory())
  {
   f.mkdirs();
  }
 }
}

MainActivity.Class:


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{
 private ProgressDialog mProgressDialog;

 String Url="http://hasmukh/hb.zip";
 String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipFolder/";
 String StorezipFileLocation =Environment.getExternalStorageDirectory() + "/DownloadedZip"; 
 String DirectoryName=Environment.getExternalStorageDirectory() + "/unzipFolder/files/";

 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  DownloadZipfile mew = new DownloadZipfile();
  mew.execute(url);

 }
}

//-This is method is used for Download Zip file from server and store in Desire location.
class DownloadZipfile extends AsyncTask<String, String, String>
{
 String result ="";
 @Override
 protected void onPreExecute()
 {
  super.onPreExecute();
  mProgressDialog = new ProgressDialog(MainActivity.this);
  mProgressDialog.setMessage("Downloading...");
  mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  mProgressDialog.setCancelable(false);
  mProgressDialog.show();
 }

 @Override
 protected String doInBackground(String... aurl)
 {
  int count;

  try
  {
   URL url = new URL(aurl[0]);
   URLConnection conexion = url.openConnection();
   conexion.connect();
   int lenghtOfFile = conexion.getContentLength();
   InputStream input = new BufferedInputStream(url.openStream());

   OutputStream output = new FileOutputStream(StorezipFileLocation);

   byte data[] = new byte[1024];
   long total = 0;

   while ((count = input.read(data)) != -1)
   {
    total += count;
    publishProgress(""+(int)((total*100)/lenghtOfFile));
    output.write(data, 0, count);
   }
   output.close();
   input.close();
   result = "true";

  } catch (Exception e) {

   result = "false";
  }
  return null;

 }
 protected void onProgressUpdate(String... progress)
 {
  Log.d("ANDRO_ASYNC",progress[0]);
  mProgressDialog.setProgress(Integer.parseInt(progress[0]));
 }

 @Override
 protected void onPostExecute(String unused)
 {
  mProgressDialog.dismiss();
  if(result.equalsIgnoreCase("true"))
  {
   try
   {
    unzip();
   } catch (IOException e)
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  else
  {

  }
 }
}
//This is the method for unzip file which is store your location. And unzip folder will store as per your desire location.

public void unzip() throws IOException 
{
 mProgressDialog = new ProgressDialog(MainActivity.this);
 mProgressDialog.setMessage("Please Wait...");
 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
 mProgressDialog.setCancelable(false);
 mProgressDialog.show();
 new UnZipTask().execute(StorezipFileLocation, DirectoryName);
}


private class UnZipTask extends AsyncTask<String, Void, Boolean> 
{
 @SuppressWarnings("rawtypes")
 @Override
 protected Boolean doInBackground(String... params) 
 {
  String filePath = params[0];
  String destinationPath = params[1];

  File archive = new File(filePath);
  try 
  {
   ZipFile zipfile = new ZipFile(archive);
   for (Enumeration e = zipfile.entries(); e.hasMoreElements();) 
   {
    ZipEntry entry = (ZipEntry) e.nextElement();
    unzipEntry(zipfile, entry, destinationPath);
   }


   UnzipUtil d = new UnzipUtil(StorezipFileLocation, DirectoryName); 
   d.unzip();

  } 
  catch (Exception e) 
  {
   return false;
  }

  return true;
 }

 @Override
 protected void onPostExecute(Boolean result) 
 {
  mProgressDialog.dismiss(); 

 }


 private void unzipEntry(ZipFile zipfile, ZipEntry entry,String outputDir) throws IOException 
 {

  if (entry.isDirectory()) 
  {
   createDir(new File(outputDir, entry.getName()));
   return;
  }

  File outputFile = new File(outputDir, entry.getName());
  if (!outputFile.getParentFile().exists())
  {
   createDir(outputFile.getParentFile());
  }

  // Log.v("", "Extracting: " + entry);
  BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
  BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

  try 
  {

  }
  finally 
  {
   outputStream.flush();
   outputStream.close();
   inputStream.close();
  }
 }

 private void createDir(File dir) 
 {
  if (dir.exists()) 
  {
   return;
  }
  if (!dir.mkdirs()) 
  {
   throw new RuntimeException("Can not create dir " + dir);
  }
 }}
}

Note: Do not forgot to add below  permission in android Manifest.xml file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

21 Aug 2013

Crop image in circular shape in android

Hello Friends,

Today i am sharing  cropping an image and convert it into circular shape. Following Class will helps you to convert an image into circular shape.



There is two method i am posting here for cropping rounded images.


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

public class GraphicsUtil 
{ 
 public Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
  Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(output);

  final int color = 0xffff0000;
  final Paint paint = new Paint();
  final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
  final RectF rectF = new RectF(rect);

  paint.setAntiAlias(true);
  paint.setDither(true);
  paint.setFilterBitmap(true);
  canvas.drawARGB(0, 0, 0, 0);
  paint.setColor(color);
  canvas.drawOval(rectF, paint);

  paint.setColor(Color.BLUE);
  paint.setStyle(Paint.Style.STROKE);
  paint.setStrokeWidth((float) 4);
  paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
  canvas.drawBitmap(bitmap, rect, rect, paint);

  return output;
 }

 public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
  int targetWidth = 125;
  int targetHeight = 125;
  Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
    targetHeight,Bitmap.Config.ARGB_8888);

  Canvas canvas = new Canvas(targetBitmap);
  Path path = new Path();
  path.addCircle(((float) targetWidth - 1) / 2,
    ((float) targetHeight - 1) / 2,
    (Math.min(((float) targetWidth), 
      ((float) targetHeight)) / 2),
      Path.Direction.CCW);

  canvas.clipPath(path);
  Bitmap sourceBitmap = scaleBitmapImage;
  canvas.drawBitmap(sourceBitmap, 
    new Rect(0, 0, sourceBitmap.getWidth(),
      sourceBitmap.getHeight()), 
      new Rect(0, 0, targetWidth,
        targetHeight), null);
  return targetBitmap;
 }

}

MainActivity.Class
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener 
{

 // keep track of camera capture intent
 final int CAMERA_CAPTURE = 1;
 // keep track of cropping intent
 final int PIC_CROP = 2;
 // captured picture uri
 private Uri picUri;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // retrieve a reference to the UI button
  Button captureBtn = (Button) findViewById(R.id.capture_btn);
  // handle button clicks
  captureBtn.setOnClickListener(this);
 }

 /**
  * Click method to handle user pressing button to launch camera
  */
 public void onClick(View v) 
 {
  if (v.getId() == R.id.capture_btn) 
  {
   try 
   {
    // use standard intent to capture an image
    Intent captureIntent = new Intent(
      MediaStore.ACTION_IMAGE_CAPTURE);
    // we will handle the returned data in onActivityResult
    startActivityForResult(captureIntent, CAMERA_CAPTURE);
   }
   catch (ActivityNotFoundException anfe) 
   {
    // display an error message
    String errorMessage = "Whoops - your device doesn't support capturing images!";
    Toast toast = Toast.makeText(this, errorMessage,Toast.LENGTH_SHORT);
    toast.show();
   }
  }
 }

 /**
  * Handle user returning from both capturing and cropping the image
  */
 protected void onActivityResult(int requestCode, int resultCode, Intent data)
 {
  if (resultCode == RESULT_OK) 
  {
   // user is returning from capturing an image using the camera
   if (requestCode == CAMERA_CAPTURE) 
   {
    // get the Uri for the captured image
    picUri = data.getData();
    // carry out the crop operation
    performCrop();
   }
   // user is returning from cropping the image
   else if (requestCode == PIC_CROP) 
   {
    // get the returned data
    Bundle extras = data.getExtras();
    // get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");
    // retrieve a reference to the ImageView
    ImageView picView = (ImageView) findViewById(R.id.picture);
    // display the returned cropped image

    GraphicsUtil graphicUtil = new GraphicsUtil();
    //picView.setImageBitmap(graphicUtil.getRoundedShape(thePic));
    picView.setImageBitmap(graphicUtil.getCircleBitmap(thePic, 16));
   }
  }
 }

 /**
  * Helper method to carry out crop operation
  */
 private void performCrop() 
 {
  // take care of exceptions
  try {
   // call the standard crop action intent (the user device may not
   // support it)
   Intent cropIntent = new Intent("com.android.camera.action.CROP");
   // indicate image type and Uri
   cropIntent.setDataAndType(picUri, "image/*");
   // set crop properties
   cropIntent.putExtra("crop", "true");
   // indicate aspect of desired crop
   cropIntent.putExtra("aspectX", 1);
   cropIntent.putExtra("aspectY", 1);
   // indicate output X and Y
   cropIntent.putExtra("outputX", 256);
   cropIntent.putExtra("outputY", 256);
   // retrieve data on return
   cropIntent.putExtra("return-data", true);
   // start the activity - we handle returning in onActivityResult
   startActivityForResult(cropIntent, PIC_CROP);
  }
  // respond to users whose devices do not support the crop action
  catch (ActivityNotFoundException anfe) {
   // display an error message
   String errorMessage = "Whoops - your device doesn't support the crop action!";
   Toast toast = Toast
     .makeText(this, errorMessage, Toast.LENGTH_SHORT);
   toast.show();
  }
 }
}

More reference link

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)