8 code snippets for Android developers

This is for all the lazy people.
I listed 8 common tasks that Android developers usually face, it’s the kind of stuff that interrupts your train of tought and makes you think “Oh God.. this is boring and I have other things to do, let’s google for some code”.
And here it is. In no particular order.
Just copy and paste, no questions asked.

  1. How to rotate a Bitmap in Android
  2. How to copy a file in Android (the smart way)
  3. How to delete a directory in Android
  4. How to convert a byte array into an hexadecimal String
  5. How to convert Android dips to pixels
  6. How to copy a directory in Android
  7. How to extract a zip archive in Android
  8. How to zip a file or a directory in Android

And let’s go!

Nr. 1 – How to rotate a Bitmap in Android

This will rotate any Bitmap to the desired angle, in degrees.

/**
 * Rotates a Bitmap
 * @param Bitmap the Bitmap object to rotate
 * @param angle the rotation angle in degrees
 * @return the rotated Bitmap
 */
public static Bitmap rotateBitmap(final Bitmap source, final float angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

Nr. 2 – How to copy a file in Android

The smart way, without that nasty new buffer[1024] thing.

public static void copyFile(final File src, final File dst) throws IOException {
    FileInputStream inStream = null;
    FileOutputStream outStream = null;

    try {
        inStream = new FileInputStream(src);
        outStream = new FileOutputStream(dst);
        FileChannel inChannel = inStream.getChannel();
        FileChannel outChannel = outStream.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } catch (IOException e) {
        throw e;
    } finally {
        if (inStream != null) inStream.close();
        if (outStream != null) outStream.close();
    }
}

Nr. 3 – How to delete a directory in Android

Yes, the directory itself and all the files and subdirectories recursively.

public static void deleteDirectory(final File directory) {
    if( directory.exists() ) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
               if (files[i].isDirectory()) {
                   deleteDirectory(files[i]);
               }
               files[i].delete();
            }
        }
        directory.delete();
    }
}

Nr 4. – How to convert a byte array into an hexadecimal String

I will probably google this in the future and find my own post.

private final static String HEX = "0123456789ABCDEF";

private static void appendHex(final StringBuffer sb, final byte b) {
    sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}

public static String toHex(final byte[] buf) {
    if (buf == null) return "";

    StringBuffer result = new StringBuffer(2 * buf.length);

    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}

Nr 5. – How to convert Android dips to pixels

You are welcome.

public static int dipToPixels(final Context context, final float dipValue) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}

Nr 6. – How to copy a directory in Android

Again yes, the directory itself and all the files and subdirectories recursively.

// If targetLocation does not exist, it will be created.
public static void copyDirectory(final File sourceLocation, final File targetLocation)
         throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists() && !targetLocation.mkdirs()) {
            throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
        }

        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
        }
    } else {

        File directory = targetLocation.getParentFile();
        if (directory != null && !directory.exists() && !directory.mkdirs()) {
            throw new IOException("Cannot create dir " + directory.getAbsolutePath());
        }

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[4096];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
}

Nr 7. – How to extract a zip archive in Android

This will extract any zip archive to the desired location on the filesystem.

public static void unzipArchive(String archivePath, String outputBasePath) throws IOException {
    final int BUFFER = 2048;

    File outputFileBasePath = new File(outputBasePath);
    if (outputFileBasePath.exists() == false) outputFileBasePath.mkdirs();

    FileInputStream fis = new FileInputStream(archivePath);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));

    ZipEntry zipEntry = zis.getNextEntry();

    while (zipEntry != null) {

        String entryFullPath = outputBasePath + File.separator + zipEntry.getName();
        File entryFile = new File(entryFullPath);
        entryFile.getParentFile().mkdirs();
        entryFile.createNewFile();

        byte data[] = new byte[BUFFER];
        FileOutputStream fos = new FileOutputStream(entryFile);

        int c;
        while ((c = zis.read(data)) != -1) {
            fos.write(data, 0, c);
        }

        fos.close();
        zipEntry = zis.getNextEntry();
    }

    zis.close();
}

Nr 8. – How to zip a file or a directory in Android

This will create a zip archive from any file or folder on the filesystem.

public static void zipFileAtPath(final String sourcePath, final String toLocation) 
                throws IOException {
    final int BUFFER = 2048;
    File sourceFile = new File(sourcePath);

    FileOutputStream dest = new FileOutputStream(toLocation);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

    if (sourceFile.isDirectory()) {
        File[] files = sourceFile.listFiles();
        for (File f : files) {

        if (f.isDirectory()) zipSubFolder(out, f, sourcePath.length());
        else {
            byte data[] = new byte[BUFFER];
            FileInputStream fi = new FileInputStream(sourcePath);
            BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
            out.putNextEntry(entry);
            int count;

            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
    } else {
        byte data[] = new byte[BUFFER];
        FileInputStream fi = new FileInputStream(sourcePath);
        BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
        out.putNextEntry(entry);
        int count;

        while ((count = origin.read(data, 0, BUFFER)) != -1) {
            out.write(data, 0, count);
        }
        origin.close();
    }
    out.close();
}

private static void zipSubFolder(final ZipOutputStream out, final File folder, final int basePathLength) throws IOException {

    final int BUFFER = 2048;
    File[] fileList = folder.listFiles();

    for (File file : fileList) {
        if (file.isDirectory()) {
            zipSubFolder(out, file, basePathLength);
        } else {
            byte data[] = new byte[BUFFER];
            String unmodifiedFilePath = file.getPath();
            String relativePath = unmodifiedFilePath.substring(basePathLength);

            FileInputStream fi = new FileInputStream(unmodifiedFilePath);
            BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(relativePath);
            out.putNextEntry(entry);
            int count;

            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }

            origin.close();
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s