Sunday, December 22, 2013

How to frame a photo / bmp in Android

Today, While going though Android code I found this, I hope it will help someone else. 

 private Bitmap framePhoto(Bitmap photo) {
        final Resources r = getResources();
        final Drawable frame = r.getDrawable(com.android.internal.R.drawable.quickcontact_badge);

        final int width = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_width);
        final int height = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_height);

        frame.setBounds(0, 0, width, height);

        final Rect padding = new Rect();
        frame.getPadding(padding);

        final Rect source = new Rect(0, 0, photo.getWidth(), photo.getHeight());
        final Rect destination = new Rect(padding.left, padding.top,
                width - padding.right, height - padding.bottom);

        final int d = Math.max(width, height);
        final Bitmap b = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888);
        final Canvas c = new Canvas(b);

        c.translate((d - width) / 2.0f, (d - height) / 2.0f);
        frame.draw(c);
        c.drawBitmap(photo, source, destination, new Paint(Paint.FILTER_BITMAP_FLAG));

        return b;
    }

Saturday, December 7, 2013

FileNameMap getContentTypeFor returns null Android

I have been using this piece of code for a long time to get the mime type of the file 

FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileName);

Today, I found out that sometimes it returns null and throws an null error exception. Since there is no other option I had to come up with a class.

import java.io.File;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class MimeTypes {
    private static final Map<String, String> EXT2MIME = new HashMap<String, String>();
    private static final Map<String, String> MIME2EXT = new HashMap<String, String>();
    private MimeTypes() {
    }
    static {
        // extension to MIME type
        EXT2MIME.put("", "application/octet-stream");
        EXT2MIME.put("ai", "application/postscript");
        EXT2MIME.put("aif", "audio/x-aiff");
        EXT2MIME.put("aifc", "audio/x-aiff");
        EXT2MIME.put("aiff", "audio/x-aiff");
        EXT2MIME.put("asf", "video/x-ms-asf");
        EXT2MIME.put("asr", "video/x-ms-asf");
        EXT2MIME.put("asx", "video/x-ms-asf");
        EXT2MIME.put("au", "audio/basic");
        EXT2MIME.put("avi", "video/x-msvideo");
        EXT2MIME.put("axs", "application/olescript");
        EXT2MIME.put("bas", "text/plain");
        EXT2MIME.put("bmp", "image/bmp");
        EXT2MIME.put("c", "text/plain");
        EXT2MIME.put("cat", "application/vnd.ms-pkiseccat");
        EXT2MIME.put("cdf", "application/x-cdf");
        EXT2MIME.put("cer", "application/x-x509-ca-cert");
        EXT2MIME.put("class", "application/java-vm");
        EXT2MIME.put("clp", "application/x-msclip");
        EXT2MIME.put("cmx", "image/x-cmx");
        EXT2MIME.put("cod", "image/cis-cod");
        EXT2MIME.put("cpio", "application/x-cpio");
        EXT2MIME.put("crd", "application/x-mscardfile");
        EXT2MIME.put("crl", "application/pkix-crl");
        EXT2MIME.put("crt", "application/x-x509-ca-cert");
        EXT2MIME.put("csh", "application/x-csh");
        EXT2MIME.put("css", "text/css");
        EXT2MIME.put("dll", "application/x-msdownload");
        EXT2MIME.put("doc", "application/msword");
        EXT2MIME.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        EXT2MIME.put("doct", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
        EXT2MIME.put("dot", "application/msword");
        EXT2MIME.put("dvi", "application/x-dvi");
        EXT2MIME.put("dxr", "application/x-director");
        EXT2MIME.put("eps", "application/postscript");
        EXT2MIME.put("epub", "application/epub+zip");
        EXT2MIME.put("etx", "text/x-setext");
        EXT2MIME.put("evy", "application/envoy");
        EXT2MIME.put("flac", "audio/flac");
        EXT2MIME.put("fif", "application/fractals");
        EXT2MIME.put("flr", "x-world/x-vrml");
        EXT2MIME.put("gif", "image/gif");
        EXT2MIME.put("gtar", "application/x-gtar");
        EXT2MIME.put("gz", "application/x-gzip");
        EXT2MIME.put("h", "text/plain");
        EXT2MIME.put("hdf", "application/x-hdf");
        EXT2MIME.put("hlp", "application/winhlp");
        EXT2MIME.put("hqx", "application/mac-binhex40");
        EXT2MIME.put("hta", "application/hta");
        EXT2MIME.put("htc", "text/x-component");
        EXT2MIME.put("htm", "text/html");
        EXT2MIME.put("html", "text/html");
        EXT2MIME.put("htt", "text/webviewhtml");
        EXT2MIME.put("ico", "image/x-icon");
        EXT2MIME.put("ief", "image/ief");
        EXT2MIME.put("iii", "application/x-iphone");
        EXT2MIME.put("isp", "application/x-internet-signup");
        EXT2MIME.put("jar", "application/java-archive");
        EXT2MIME.put("jfif", "image/pipeg");
        EXT2MIME.put("jpe", "image/jpeg");
        EXT2MIME.put("jpeg", "image/jpeg");
        EXT2MIME.put("jpg", "image/jpeg");
        EXT2MIME.put("js", "application/x-javascript");
        EXT2MIME.put("json", "application/json");
        EXT2MIME.put("latex", "application/x-latex");
        EXT2MIME.put("lsf", "video/x-la-asf");
        EXT2MIME.put("lsx", "video/x-la-asf");
        EXT2MIME.put("m3u", "audio/x-mpegurl");
        EXT2MIME.put("man", "application/x-troff-man");
        EXT2MIME.put("mdb", "application/x-msaccess");
        EXT2MIME.put("me", "application/x-troff-me");
        EXT2MIME.put("mhtv", "message/rfc822");
        EXT2MIME.put("mhtml", "message/rfc822");
        EXT2MIME.put("mid", "audio/mid");
        EXT2MIME.put("mov", "video/quicktime");
        EXT2MIME.put("movie", "video/x-sgi-movie");
        EXT2MIME.put("mp2", "video/mpeg");
        EXT2MIME.put("mp3", "audio/mpeg");
        EXT2MIME.put("mpa", "video/mpeg");
        EXT2MIME.put("mpe", "video/mpegv");
        EXT2MIME.put("mpeg", "video/mpeg");
        EXT2MIME.put("mpg", "video/mpegv");
        EXT2MIME.put("mpp", "application/vnd.ms-project");
        EXT2MIME.put("mpv2", "video/mpeg");
        EXT2MIME.put("ms", "application/x-troff-ms");
        EXT2MIME.put("mvb", "application/x-msmediaview");
        EXT2MIME.put("nws", "message/rfc822");
        EXT2MIME.put("oda", "application/oda");
        EXT2MIME.put("odb", "application/vnd.oasis.opendocument.database");
        EXT2MIME.put("odc", "application/vnd.oasis.opendocument.chart");
        EXT2MIME.put("odf", "application/vnd.oasis.opendocument.formula");
        EXT2MIME.put("odft", "application/vnd.oasis.opendocument.formula-template");
        EXT2MIME.put("odg", "application/vnd.oasis.opendocument.graphics");
        EXT2MIME.put("odi", "application/vnd.oasis.opendocument.image");
        EXT2MIME.put("odm", "application/vnd.oasis.opendocument.text-master");
        EXT2MIME.put("odp", "application/vnd.oasis.opendocument.presentation");
        EXT2MIME.put("ods", "application/vnd.oasis.opendocument.spreadsheet");
        EXT2MIME.put("odt", "application/vnd.oasis.opendocument.text");
        EXT2MIME.put("ogg", "audio/ogg");
        EXT2MIME.put("ogv", "video/ogg");
        EXT2MIME.put("otc", "application/vnd.oasis.opendocument.chart-template");
        EXT2MIME.put("otg", "application/vnd.oasis.opendocument.graphics-template");
        EXT2MIME.put("oth", "application/vnd.oasis.opendocument.text-web");
        EXT2MIME.put("oti", "application/vnd.oasis.opendocument.image-template");
        EXT2MIME.put("otp", "application/vnd.oasis.opendocument.presentation-template");
        EXT2MIME.put("ots", "application/vnd.oasis.opendocument.spreadsheet-template");
        EXT2MIME.put("ott", "application/vnd.oasis.opendocument.text-template");
        EXT2MIME.put("p10", "application/pkcs10");
        EXT2MIME.put("p12", "application/x-pkcs12v");
        EXT2MIME.put("p7b", "application/x-pkcs7-certificates");
        EXT2MIME.put("p7c", "application/x-pkcs7-mime");
        EXT2MIME.put("p7m", "application/x-pkcs7-mime");
        EXT2MIME.put("p7r", "application/x-pkcs7-certreqresp");
        EXT2MIME.put("p7s", "application/x-pkcs7-signature");
        EXT2MIME.put("pbm", "image/x-portable-bitmap");
        EXT2MIME.put("pdf", "application/pdf");
        EXT2MIME.put("pfx", "application/x-pkcs12");
        EXT2MIME.put("pgm", "image/x-portable-graymap");
        EXT2MIME.put("vpko", "application/ynd.ms-pkipko");
        EXT2MIME.put("pma", "application/x-perfmon");
        EXT2MIME.put("pmc", "application/x-perfmon");
        EXT2MIME.put("pml", "application/x-perfmon");
        EXT2MIME.put("pmr", "application/x-perfmon");
        EXT2MIME.put("pmw", "application/x-perfmon");
        EXT2MIME.put("png", "image/png");
        EXT2MIME.put("pnm", "image/x-portable-anymap");
        EXT2MIME.put("pot", "application/vnd.ms-powerpoint");
        EXT2MIME.put("ppm", "image/x-portable-pixmap");
        EXT2MIME.put("pps", "application/vnd.ms-powerpoint");
        EXT2MIME.put("ppt", "application/vnd.ms-powerpoint");
        EXT2MIME.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        EXT2MIME.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
        EXT2MIME.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
        EXT2MIME.put("prf", "application/pics-rules");
        EXT2MIME.put("ps", "application/postscript");
        EXT2MIME.put("pub", "application/x-mspublisher");
        EXT2MIME.put("qt", "video/quicktime");
        EXT2MIME.put("ra", "audio/x-pn-realaudio");
        EXT2MIME.put("ram", "audio/x-pn-realaudio");
        EXT2MIME.put("ras", "image/x-cmu-raster");
        EXT2MIME.put("rgb", "image/x-rgb");
        EXT2MIME.put("rmi", "audio/mid");
        EXT2MIME.put("roff", "application/x-troff");
        EXT2MIME.put("rtf", "application/rtf");
        EXT2MIME.put("rtx", "text/richtext");
        EXT2MIME.put("ser", "application/java-serialized-object");
        EXT2MIME.put("scd", "application/x-msschedule");
        EXT2MIME.put("sct", "text/scriptlet");
        EXT2MIME.put("sh", "application/x-sh");
        EXT2MIME.put("shar", "application/x-shar");
        EXT2MIME.put("sit", "application/x-stuffit");
        EXT2MIME.put("snd", "audio/basic");
        EXT2MIME.put("spc", "application/x-pkcs7-certificates");
        EXT2MIME.put("spl", "application/futuresplash");
        EXT2MIME.put("src", "application/x-wais-source");
        EXT2MIME.put("sst", "application/vnd.ms-pkicertstore");
        EXT2MIME.put("stl", "application/vnd.ms-pkistl");
        EXT2MIME.put("stm", "text/html");
        EXT2MIME.put("svg", "image/svg+xml");
        EXT2MIME.put("swf", "application/x-shockwave-flash");
        EXT2MIME.put("t", "application/x-troff");
        EXT2MIME.put("tar", "application/x-tar");
        EXT2MIME.put("tcl", "application/x-tcl");
        EXT2MIME.put("tex", "application/x-tex");
        EXT2MIME.put("texi", "application/x-texinfo");
        EXT2MIME.put("texinfo", "application/x-texinfo");
        EXT2MIME.put("tgz", "application/x-compressed");
        EXT2MIME.put("tif", "image/tiff");
        EXT2MIME.put("tiff", "image/tiff");
        EXT2MIME.put("tr", "application/x-troff");
        EXT2MIME.put("trm", "application/x-msterminal");
        EXT2MIME.put("tsv", "text/tab-separated-values");
        EXT2MIME.put("txt", "text/plain");
        EXT2MIME.put("uls", "text/iuls");
        EXT2MIME.put("ustar", "application/x-ustar");
        EXT2MIME.put("vcf", "text/x-vcard");
        EXT2MIME.put("vrml", "x-world/x-vrml");
        EXT2MIME.put("wav", "audio/x-wav");
        EXT2MIME.put("wcm", "application/vnd.ms-works");
        EXT2MIME.put("wdb", "application/vnd.ms-works");
        EXT2MIME.put("wmf", "application/x-msmetafile");
        EXT2MIME.put("wps", "application/vnd.ms-works");
        EXT2MIME.put("wri", "application/x-mswrite");
        EXT2MIME.put("wrl", "x-world/x-vrml");
        EXT2MIME.put("wrz", "x-world/x-vrml");
        EXT2MIME.put("xaf", "x-world/x-vrml");
        EXT2MIME.put("xbm", "image/x-xbitmap");
        EXT2MIME.put("xla", "application/vnd.ms-excel");
        EXT2MIME.put("xlc", "application/vnd.ms-excel");
        EXT2MIME.put("xlm", "application/vnd.ms-excel");
        EXT2MIME.put("xls", "application/vnd.ms-excel");
        EXT2MIME.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        EXT2MIME.put("xlt", "application/vnd.ms-excel");
        EXT2MIME.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
        EXT2MIME.put("xlw", "application/vnd.ms-excel");
        EXT2MIME.put("xml", "text/xml");
        EXT2MIME.put("xof", "x-world/x-vrml");
        EXT2MIME.put("xpm", "image/x-xpixmap");
        EXT2MIME.put("xwd", "image/x-xwindowdump");
        EXT2MIME.put("z", "application/x-compress");
        EXT2MIME.put("zip", "application/zip");
        // MIME type to extension
        MIME2EXT.put("application/octet-stream", "");
        MIME2EXT.put("application/envoy", "evy");
        MIME2EXT.put("application/epub+zip", "epub");
        MIME2EXT.put("application/fractals", "fif");
        MIME2EXT.put("application/futuresplash", "spl");
        MIME2EXT.put("application/hta", "hta");
        MIME2EXT.put("application/java-archive", "jar");
        MIME2EXT.put("application/java-serialized-object", "ser");
        MIME2EXT.put("application/java-vm", "class");
        MIME2EXT.put("application/javascript", "js");
        MIME2EXT.put("application/json", "json");
        MIME2EXT.put("application/mac-binhex40", "hqx");
        MIME2EXT.put("application/msword", "doc");
        MIME2EXT.put("application/oda", "oda");
        MIME2EXT.put("application/olescript", "axs");
        MIME2EXT.put("application/pdf", "pdf");
        MIME2EXT.put("application/pics-rules", "prf");
        MIME2EXT.put("application/pkcs10", "p10");
        MIME2EXT.put("application/pkix-crl", "crl");
        MIME2EXT.put("application/postscript", "ps");
        MIME2EXT.put("application/rtf", "rtf");
        MIME2EXT.put("application/vnd.ms-excel", "xls");
        MIME2EXT.put("application/vnd.ms-pkicertstore", "sst");
        MIME2EXT.put("application/vnd.ms-pkiseccat", "cat");
        MIME2EXT.put("application/vnd.ms-pkistl", "stl");
        MIME2EXT.put("application/vnd.ms-powerpoint", "ppt");
        MIME2EXT.put("application/vnd.ms-project", "mpp");
        MIME2EXT.put("application/vnd.ms-works", "wps");
        MIME2EXT.put("application/vnd.oasis.opendocument.chart", "odc");
        MIME2EXT.put("application/vnd.oasis.opendocument.chart-template", "otc");
        MIME2EXT.put("application/vnd.oasis.opendocument.database", "odb");
        MIME2EXT.put("application/vnd.oasis.opendocument.formula", "odf");
        MIME2EXT.put("application/vnd.oasis.opendocument.formula-template", "odft");
        MIME2EXT.put("application/vnd.oasis.opendocument.graphics", "odg");
        MIME2EXT.put("application/vnd.oasis.opendocument.graphics-template", "otg");
        MIME2EXT.put("application/vnd.oasis.opendocument.image", "odi");
        MIME2EXT.put("application/vnd.oasis.opendocument.image-template", "oti");
        MIME2EXT.put("application/vnd.oasis.opendocument.presentation", "odp");
        MIME2EXT.put("application/vnd.oasis.opendocument.presentation-template", "otp");
        MIME2EXT.put("application/vnd.oasis.opendocument.spreadsheet", "ods");
        MIME2EXT.put("application/vnd.oasis.opendocument.spreadsheet-template", "ots");
        MIME2EXT.put("application/vnd.oasis.opendocument.text", "odt");
        MIME2EXT.put("application/vnd.oasis.opendocument.text-master", "odm");
        MIME2EXT.put("application/vnd.oasis.opendocument.text-template", "ott");
        MIME2EXT.put("application/vnd.oasis.opendocument.text-web", "oth");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.presentationml.template", "potx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx");
        MIME2EXT.put("application/winhlp", "hlp");
        MIME2EXT.put("application/x-cdf", "cdf");
        MIME2EXT.put("application/x-compress", "z");
        MIME2EXT.put("application/x-compressed", "tgz");
        MIME2EXT.put("application/x-cpio", "cpio");
        MIME2EXT.put("application/x-csh", "csh");
        MIME2EXT.put("application/x-director", "dxr");
        MIME2EXT.put("application/x-dvi", "dvi");
        MIME2EXT.put("application/x-gtar", "gtar");
        MIME2EXT.put("application/x-gzip", "gz");
        MIME2EXT.put("application/x-hdf", "hdf");
        MIME2EXT.put("application/x-internet-signup", "isp");
        MIME2EXT.put("application/x-iphone", "iii");
        MIME2EXT.put("application/x-javascript", "js");
        MIME2EXT.put("application/x-latex", "latex");
        MIME2EXT.put("application/x-msaccess", "mdb");
        MIME2EXT.put("application/x-mscardfile", "crd");
        MIME2EXT.put("application/x-msclip", "clp");
        MIME2EXT.put("application/x-msdownload", "dll");
        MIME2EXT.put("application/x-msmediaview", "mvb");
        MIME2EXT.put("application/x-msmetafile", "wmf");
        MIME2EXT.put("application/x-mspublisher", "pub");
        MIME2EXT.put("application/x-msschedule", "scd");
        MIME2EXT.put("application/x-msterminal", "trm");
        MIME2EXT.put("application/x-mswrite", "wri");
        MIME2EXT.put("application/x-perfmon", "pmw");
        MIME2EXT.put("application/x-pkcs12", "pfx");
        MIME2EXT.put("application/x-pkcs12v", "p12");
        MIME2EXT.put("application/x-pkcs7-certificates", "p7b");
        MIME2EXT.put("application/x-pkcs7-certificates", "spc");
        MIME2EXT.put("application/x-pkcs7-certreqresp", "p7r");
        MIME2EXT.put("application/x-pkcs7-mime", "p7m");
        MIME2EXT.put("application/x-pkcs7-signature", "p7s");
        MIME2EXT.put("application/x-sh", "sh");
        MIME2EXT.put("application/x-shar", "shar");
        MIME2EXT.put("application/x-shockwave-flash", "swf");
        MIME2EXT.put("application/x-stuffit", "sit");
        MIME2EXT.put("application/x-tar", "tar");
        MIME2EXT.put("application/x-tcl", "tcl");
        MIME2EXT.put("application/x-tex", "tex");
        MIME2EXT.put("application/x-texinfo", "texinfo");
        MIME2EXT.put("application/x-troff-man", "man");
        MIME2EXT.put("application/x-troff-me", "me");
        MIME2EXT.put("application/x-troff-ms", "ms");
        MIME2EXT.put("application/x-troff", "tr");
        MIME2EXT.put("application/x-ustar", "ustar");
        MIME2EXT.put("application/x-wais-source", "src");
        MIME2EXT.put("application/x-x509-ca-cert", "cer");
        MIME2EXT.put("application/ynd.ms-pkipko", "vpko");
        MIME2EXT.put("application/zip", "zip");
        MIME2EXT.put("audio/basic", "snd");
        MIME2EXT.put("audio/flac", "flac");
        MIME2EXT.put("audio/mid", "mid");
        MIME2EXT.put("audio/mpeg", "mp3");
        MIME2EXT.put("audio/ogg", "ogg");
        MIME2EXT.put("audio/x-aiff", "aif");
        MIME2EXT.put("audio/x-mpegurl", "m3u");
        MIME2EXT.put("audio/x-pn-realaudio", "ram");
        MIME2EXT.put("audio/x-wav", "wav");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.wordprocessingml.template", "doct");
        MIME2EXT.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
        MIME2EXT.put("image/bmp", "bmp");
        MIME2EXT.put("image/cis-cod", "cod");
        MIME2EXT.put("image/gif", "gif");
        MIME2EXT.put("image/ief", "ief");
        MIME2EXT.put("image/jpeg", "jpeg");
        MIME2EXT.put("image/pipeg", "jfif");
        MIME2EXT.put("image/png", "png");
        MIME2EXT.put("image/svg+xml", "svg");
        MIME2EXT.put("image/tiff", "tiff");
        MIME2EXT.put("image/x-cmu-raster", "ras");
        MIME2EXT.put("image/x-cmx", "cmx");
        MIME2EXT.put("image/x-icon", "ico");
        MIME2EXT.put("image/x-portable-anymap", "pnm");
        MIME2EXT.put("image/x-portable-bitmap", "pbm");
        MIME2EXT.put("image/x-portable-graymap", "pgm");
        MIME2EXT.put("image/x-portable-pixmap", "ppm");
        MIME2EXT.put("image/x-rgb", "rgb");
        MIME2EXT.put("image/x-xbitmap", "xbm");
        MIME2EXT.put("image/x-xpixmap", "xpm");
        MIME2EXT.put("image/x-xwindowdump", "xwd");
        MIME2EXT.put("message/rfc822", "mhtml");
        MIME2EXT.put("text/css", "css");
        MIME2EXT.put("text/html", "html");
        MIME2EXT.put("text/iuls", "uls");
        MIME2EXT.put("text/plain", "txt");
        MIME2EXT.put("text/richtext", "rtx");
        MIME2EXT.put("text/scriptlet", "sct");
        MIME2EXT.put("text/tab-separated-values", "tsv");
        MIME2EXT.put("text/webviewhtml", "htt");
        MIME2EXT.put("text/x-component", "htc");
        MIME2EXT.put("text/x-setext", "etx");
        MIME2EXT.put("text/x-vcard", "vcf");
        MIME2EXT.put("text/xml", "xml");
        MIME2EXT.put("video/mpeg", "mpeg");
        MIME2EXT.put("video/mpegv", "mpe");
        MIME2EXT.put("video/ogg", "ogv");
        MIME2EXT.put("video/quicktime", "mov");
        MIME2EXT.put("video/quicktime", "qt");
        MIME2EXT.put("video/x-la-asf", "lsf");
        MIME2EXT.put("video/x-la-asf", "lsx");
        MIME2EXT.put("video/x-ms-asf", "asf");
        MIME2EXT.put("video/x-msvideo", "avi");
        MIME2EXT.put("video/x-sgi-movie", "movie");
        MIME2EXT.put("x-world/x-vrml", "vrml");
    }
    /**
     * Returns the MIME type for file extension.
     */
    public static String getMIMEType(String ext) {
        if (ext == null) {
            return EXT2MIME.get("");
        }
        int x = ext.lastIndexOf('.');
        if (x > -1) {
            ext = ext.substring(x + 1);
        }
        String mime = EXT2MIME.get(ext.toLowerCase());
        if (mime == null) {
            mime = URLConnection.getFileNameMap().getContentTypeFor("x." + ext);
        }
        if (mime == null) {
            mime = EXT2MIME.get("");
        }
        return mime;
    }
    /**
     * Returns the MIME type for a file.
     */
    public static String getMIMEType(File file) {
        if (file == null) {
            return getMIMEType("");
        }
        return getMIMEType(file.getName());
    }
    /**
     * Guesses a extension from a MIME type.
     */
    public static String getExtension(String mimeType) {
        if (mimeType == null) {
            return "";
        }
        int x = mimeType.indexOf(';');
        if (x > -1) {
            mimeType = mimeType.substring(0, x);
        }
        mimeType = mimeType.trim().toLowerCase(Locale.ENGLISH);
        String extension = MIME2EXT.get(mimeType);
        return ((extension == null || extension.length() == 0) ? "" : "." + extension);
    }
}

Wednesday, November 20, 2013

Android Google+ example “An internal error occured” error

Today I was going through how to integrate Google + Sign-in button on Android. I was following the tutorial here

After completing all the steps. When i clicked on "Sign in" button I am getting a tooltip with “An internal error occured” error. To fix this problem I did few things and I am not sure which one worked.

1. Make sure to use the same SHA1 fingerprint in Google console when you create a "registered apps"

2. Change

mPlusClient = new PlusClient.Builder(this, this, this)
                .setVisibleActivities("XXXX/AddActivity", "XXXX/BuyActivity")
                .setScopes("PLUS_LOGIN")  // Space separated list of scopes
                .build();

To 
mPlusClient = new PlusClient.Builder(this, this, this)
        .setVisibleActivities("XXXX/AddActivity", "XXXX/BuyActivity")
        .build();

Friday, November 8, 2013

Parse the result of ls command in Java Android


Today I wanted to process the output from ls command.  After few mins Gooling and modiyfing I came  up with this, Hope it will help someone else
package com.test;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class FileListingUtil {
/** Entry type: File */
public static final int TYPE_FILE = 0;
/** Entry type: Directory */
public static final int TYPE_DIRECTORY = 1;
/** Entry type: Directory Link */
public static final int TYPE_DIRECTORY_LINK = 2;
/** Entry type: Block */
public static final int TYPE_BLOCK = 3;
/** Entry type: Character */
public static final int TYPE_CHARACTER = 4;
/** Entry type: Link */
public static final int TYPE_LINK = 5;
/** Entry type: Socket */
public static final int TYPE_SOCKET = 6;
/** Entry type: FIFO */
public static final int TYPE_FIFO = 7;
/** Entry type: Other */
public static final int TYPE_OTHER = 8;
/** Device side file separator. */
public static final String FILE_SEPARATOR = "/"; //$NON-NLS-1$
/**
* Regexp pattern to parse the result from ls.
*/
private static Pattern sLsPattern = Pattern
.compile("^([bcdlsp-][-r][-w][-xsS][-r][-w][-xsS][-r][-w][-xstST])\\s+(\\S+)\\s+(\\S+)\\s+([\\d\\s,]*)\\s+(\\d{4}-\\d\\d-\\d\\d)\\s+(\\d\\d:\\d\\d)\\s+(.*)$"); //$NON-NLS-1$
public List<FileEntry> processNewLines(String[] lines) {
List<FileEntry> listOfFiles = new ArrayList<FileEntry>();
for (String line : lines) {
// no need to handle empty lines.
if (line.length() == 0) {
continue;
}
// run the line through the regexp
Matcher m = sLsPattern.matcher(line);
if (m.matches() == false) {
continue;
}
// get the name
String name = m.group(7);
// get the rest of the groups
String permissions = m.group(1);
String owner = m.group(2);
String group = m.group(3);
String size = m.group(4);
String date = m.group(5);
String time = m.group(6);
String info = null;
// and the type
int objectType = TYPE_OTHER;
switch (permissions.charAt(0)) {
case '-':
objectType = TYPE_FILE;
break;
case 'b':
objectType = TYPE_BLOCK;
break;
case 'c':
objectType = TYPE_CHARACTER;
break;
case 'd':
objectType = TYPE_DIRECTORY;
break;
case 'l':
objectType = TYPE_LINK;
break;
case 's':
objectType = TYPE_SOCKET;
break;
case 'p':
objectType = TYPE_FIFO;
break;
}
// now check what we may be linking to
if (objectType == TYPE_LINK) {
String[] segments = name.split("\\s->\\s"); //$NON-NLS-1$
// we should have 2 segments
if (segments.length == 2) {
// update the entry name to not contain the link
name = segments[0];
// and the link name
info = segments[1];
// now get the path to the link
String[] pathSegments = info.split(FILE_SEPARATOR);
if (pathSegments.length == 1) {
// the link is to something in the same directory,
// unless the link is ..
if ("..".equals(pathSegments[0])) { //$NON-NLS-1$
// set the type and we're done.
objectType = TYPE_DIRECTORY_LINK;
} else {
// either we found the object already
// or we'll find it later.
}
}
}
// add an arrow in front to specify it's a link.
info = "-> " + info; //$NON-NLS-1$;
}
FileEntry entry = new FileEntry();
entry.permissions = permissions;
entry.size = size;
entry.date = date;
entry.time = time;
entry.owner = owner;
entry.group = group;
if (objectType == TYPE_LINK) {
entry.info = info;
}
listOfFiles.add(entry);
}
return listOfFiles;
}
public final static class FileEntry {
String name;
String info;
String permissions;
String size;
String date;
String time;
String owner;
String group;
int type;
}
}

Monday, September 16, 2013

FileNotFoundException when accessing file stored at /storage/emulated/0 in Android

I am keep getting this error on my Android Nexus 4 device and it is becoming a headache now. Even though I have permission to access SDCard still my application can not read images from the galley.

If you take a picture from the Android camera path is saved as /storage/emulated/0/DCIM/... and when my app try to read this file from it throws FileNotFoundException  error. Weird... To fix this

I did this

String path = path .replace(“/storage/emulated/0″, “/sdcard”); 

and it worked!


Tuesday, July 16, 2013

how to remove invalid XML characters from a string in java

private static String stripInvalidXMLChars(CharSequence cs) {
        StringBuffer ret = new StringBuffer();
        char ch;
        /* http://www.w3.org/TR/xml11/#charsets
        [#x1-#x8], [#xB-#xC], [#xE-#x1F], [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF],
        [#x1FFFE-#x1FFFF], [#x2FFFE-#x2FFFF], [#x3FFFE-#x3FFFF],
        [#x4FFFE-#x4FFFF], [#x5FFFE-#x5FFFF], [#x6FFFE-#x6FFFF],
        [#x7FFFE-#x7FFFF], [#x8FFFE-#x8FFFF], [#x9FFFE-#x9FFFF],
        [#xAFFFE-#xAFFFF], [#xBFFFE-#xBFFFF], [#xCFFFE-#xCFFFF],
        [#xDFFFE-#xDFFFF], [#xEFFFE-#xEFFFF], [#xFFFFE-#xFFFFF],
        [#x10FFFE-#x10FFFF].
         */
        for (int i = 0; i < cs.length(); i++) {
            ch = cs.charAt(i);

            if((ch >= 0x1 && ch <= 0x8) || (ch >= 0xB && ch <= 0xC) || (ch >= 0xE && ch <= 0x1F) ||
                    (ch >= 0x7F && ch <= 0x84) || (ch >= 0x86 && ch <= 0x9f) ||
                    (ch >= 0xFDD0 && ch <= 0xFDDF) || (ch >= 0x1FFFE && ch <= 0x1FFFF) ||
                    (ch >= 0x2FFFE && ch <= 0x2FFFF) || (ch >= 0x3FFFE && ch <= 0x3FFFF) ||
                   (ch >= 0x4FFFE && ch <= 0x4FFFF) || (ch >= 0x5FFFE && ch <= 0x5FFFF) ||
                    (ch >= 0x6FFFE && ch <= 0x6FFFF) || (ch >= 0x7FFFE && ch <= 0x7FFFF) ||
                    (ch >= 0x8FFFE && ch <= 0x8FFFF) || (ch >= 0x9FFFE && ch <= 0x9FFFF) ||
                    (ch >= 0xAFFFE && ch <= 0xAFFFF) || (ch >= 0xBFFFE && ch <= 0xBFFFF) ||
                    (ch >= 0xCFFFE && ch <= 0xCFFFF) || (ch >= 0xDFFFE && ch <= 0xDFFFF) ||
                    (ch >= 0xEFFFE && ch <= 0xEFFFF) || (ch >= 0xFFFFE && ch <= 0xFFFFF) ||
                    (ch >= 0x10FFFE && ch <= 0x10FFFF))
                ret.append(".");
            else
                ret.append(ch);
        }
        return ret.toString();
    }
}

Thursday, May 30, 2013

Android 4.2 adb offline issue in Nexus 4 and Samsung S4

Today I plugged in Samsung S4 and it did not show up in the adb. So I tried my Nexus 4 and it did not show up either. When I tried S2 it worked. So I thought it's must be something in Android 4.

So I updated the SDK via SDK Manager.exe and still did not solve this problem. When I looked at the adb Android documentation it says

When you connect a device running Android 4.2.2 or higher to your computer, the system shows a dialog asking whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices because it ensures that USB debugging and other adb commands cannot be executed unless you're able to unlock the device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android 4.2.2 or higher.

When i checked my adb version after updating, it was still 1.0.29, strange somehow it did not download 1.0.31. So I downloaded the latest tool set from http://developer.android.com/sdk/index.html and copied the platform-tools folder to my existing folder and I did "adb version" and got 1.0.31. Now when I tried "adb devices" still not getting the device. Finally  I unplugged the USB cable and re-connected and It worked.

Make sure to check "trust this computer" so it will save the settings.

Tuesday, May 28, 2013

VerifyError : Verifier rejected class errors in Android + ProGuard


Today, all of the sudden we started getting


VFY: Ljava/lang/Object; is not instance of Ljava/lang/String;
VFY: bad arg 0 (into Ljava/lang/String;)
VFY:  rejecting call to Ljava/lang/String;.format (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
VFY:  rejecting opcode 0x71 at 0x01e4


It is kind of frustrating when you see errors like this in LogCat with out pin-pointing where is the actual problem is. Once the code gets obfuscated, it is no longer the code we used to work on.  First enable the mapping in ProGuard . ProGuard  creates a nice map on which methods and properties get renamed to what, it is easy to track down which method is causing the problem.

In my case, I found out which function is causing the problem but that did not mean there is a problem with the code, because real code worked fine and after obfuscating only started having above issue.

When i Googled bit more I came across this post in StackOverflow

http://stackoverflow.com/questions/4980047/proguard-error-with-method-signatures

he suggests to move to the latest version of the ProGuard. I was on ProGuard 4.5 and when changed it to use ProGuard 4.9 it worked !

From what I understood, problem is during the run-time is looking for a class that is no longer there and it's causing this exception. During the obfuscating process it did something to String.Format and whole thing fell apart .

Wednesday, February 20, 2013

How to show/prompt login every time user returns or open the application

Today, I wanted to know how to show the application login when a user opens or returns to the application every-time. Most difficult part about this is how to get rid of activities popping out from the stack history.

This is how I did it.

I marked the main activity as



  <activity
            android:name=".ui.MainSettingsActivity" android:label="@string/app_name" android:launchMode="singleTop" android:clearTaskOnLaunch="true" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



and prompt for password in `onCreate` and `onNewIntent` in the Activity.java worked like a charm

This way, if the user open a new instance or use a existing from from stack history we can popup for the password.

Key part here is "singleTop".

If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to itsonNewIntent() method, rather than creating a new instance of the activity.


Monday, January 21, 2013

MediaPlayer prepare failed. status=0x1 or other issues related to MediaPlayer in Android

If you are working with Android's MediaPlayer you must have seen error popping up like this so randomly and it's quite frustrating .

After digging in I figure out the easy way to diagnose issues related to this.

First thing you should do is hook up setOnErrorListener

because it gives you a correct error codes related to the error.


mediaPlayer.setOnErrorListener(new OnErrorListener() {
    public boolean onError(MediaPlayer mp, int what, int extra) {
        onPlaybackError();
        return true;
    }
});

Eg,


E/MediaPlayer(): error (1, -17)

When it comes to error codes, Android documentation sucks. You have to go to the source code to look after the error codes to find out whats wrong

Error codes are located here 

In this case it was

const PVMFStatus PVMFErrResource = (-17);

Error due to general error in underlying resource

After some more digging i found out the reason for this error.

Android has a total of 8 instances of the player to share among all apps.

 You are likely to get this error if you have ran out. so watch out!!

Tuesday, January 15, 2013

How to check whether a content provider is installed ?

Today, I had to research on the calender to read the events from the native Android calender. Problem is different version of Android uses different content providers. So, how to find if calendar content provider exists ?


private boolean isCalenderExisit(Activity activity) {
boolean isSuccess = false;
ContentProviderClient calendarClient = activity.getContentResolver().acquireContentProviderClient(
getContentURI());
ContentProviderClient eventClient = activity.getContentResolver().acquireContentProviderClient(
getContentURI());
if (eventClient == null || calendarClient == null) {
isSuccess = false;
}
else {
calendarClient.release();
eventClient.release();
isSuccess = true;
}

return isSuccess;
}
public static Uri getContentURI() {
final Uri CONTENT_URI_PRE_8 = Uri.parse("content://calendar/calendars");
final Uri CONTENT_URI = Uri.parse("content://com.android.calendar/calendars");
if(Build.VERSION.SDK_INT <= 7) {
return CONTENT_URI_PRE_8;
} else {
return CONTENT_URI;
}
}