Example usage for android.graphics BitmapFactory decodeByteArray

List of usage examples for android.graphics BitmapFactory decodeByteArray

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeByteArray.

Prototype

public static Bitmap decodeByteArray(byte[] data, int offset, int length) 

Source Link

Document

Decode an immutable bitmap from the specified byte array.

Usage

From source file:com.handpoint.headstart.client.ui.ReceiptActivity.java

private Bitmap getImageBitmap() {
    if (null != mBasketItem && null != mBasketItem.getThumbnail()) {
        int len = mBasketItem.getThumbnail().length;
        return BitmapFactory.decodeByteArray(mBasketItem.getThumbnail(), 0, len);
    }//from  ww w  .j  a  v a  2 s. co  m
    return null;
}

From source file:net.ben.subsonic.androidapp.service.RESTMusicService.java

@Override
public Bitmap getCoverArt(Context context, MusicDirectory.Entry entry, int size, boolean saveToFile,
        ProgressListener progressListener) throws Exception {

    // Synchronize on the entry so that we don't download concurrently for the same song.
    synchronized (entry) {

        // Use cached file, if existing.
        File albumArtFile = FileUtil.getAlbumArtFile(context, entry);
        if (albumArtFile.exists()) {

            InputStream in = new FileInputStream(albumArtFile);
            try {
                byte[] bytes = Util.toByteArray(in);
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                return Bitmap.createScaledBitmap(bitmap, size, size, true);
            } finally {
                Util.close(in);//w w  w  .ja v a2s  .  c  o  m
            }
        }

        String url = Util.getRestUrl(context, "getCoverArt");

        InputStream in = null;
        try {
            List<String> parameterNames = Arrays.asList("id", "size");
            List<Object> parameterValues = Arrays.<Object>asList(entry.getCoverArt(), size);
            HttpEntity entity = getEntityForURL(context, url, null, parameterNames, parameterValues,
                    progressListener);
            in = entity.getContent();

            // If content type is XML, an error occured.  Get it.
            String contentType = Util.getContentType(entity);
            if (contentType != null && contentType.startsWith("text/xml")) {
                new ErrorParser(context).parse(new InputStreamReader(in, Constants.UTF_8));
                return null; // Never reached.
            }

            byte[] bytes = Util.toByteArray(in);

            if (saveToFile) {
                OutputStream out = null;
                try {
                    out = new FileOutputStream(albumArtFile);
                    out.write(bytes);
                } finally {
                    Util.close(out);
                }
            }

            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        } finally {
            Util.close(in);
        }
    }
}

From source file:reportsas.com.formulapp.Formulario.java

public void CapturaF() {
    if (parametroCam == null) {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);

    } else {// www. j a v a 2 s .c  o  m

        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_imagen);
        dialog.setTitle("Captura de Formulario");
        byte[] decodedByte = Base64.decode(parametroCam.getValor(), 0);

        ImageView imageview = (ImageView) dialog.findViewById(R.id.ImaVcaptura);
        Button Button1 = (Button) dialog.findViewById(R.id.NuevaToma);
        Button Button2 = (Button) dialog.findViewById(R.id.btn_cerrar);

        imageview.setImageBitmap(BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length));
        Button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 1);
                dialog.dismiss();
            }
        });

        Button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });

        dialog.show();

    }

}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

@SuppressWarnings("unchecked")
protected T transform(String url, byte[] data, AjaxStatus status) {

    if (type == null) {
        return null;
    }//from ww w . ja  v  a2 s.  c  o m

    File file = status.getFile();

    if (data != null) {

        if (type.equals(Bitmap.class)) {
            return (T) BitmapFactory.decodeByteArray(data, 0, data.length);
        }

        if (type.equals(JSONObject.class)) {

            JSONObject result = null;
            String str = null;
            try {
                str = new String(data, encoding);
                result = (JSONObject) new JSONTokener(str).nextValue();
            } catch (Exception e) {
                AQUtility.debug(e);
                AQUtility.debug(str);
            }
            return (T) result;
        }

        if (type.equals(JSONArray.class)) {

            JSONArray result = null;

            try {
                String str = new String(data, encoding);
                result = (JSONArray) new JSONTokener(str).nextValue();
            } catch (Exception e) {
                AQUtility.debug(e);
            }
            return (T) result;
        }

        if (type.equals(String.class)) {

            String result = null;

            if (status.getSource() == AjaxStatus.NETWORK) {
                AQUtility.debug("network");
                result = correctEncoding(data, encoding, status);
            } else {
                AQUtility.debug("file");
                try {
                    result = new String(data, encoding);
                } catch (Exception e) {
                    AQUtility.debug(e);
                }
            }

            return (T) result;
        }

        /*
        if(type.equals(XmlDom.class)){
                   
           XmlDom result = null;
                   
           try {    
              result = new XmlDom(data);
           } catch (Exception e) {           
              AQUtility.debug(e);
           }
                   
           return (T) result; 
        }
        */

        if (type.equals(byte[].class)) {
            return (T) data;
        }

        if (transformer != null) {
            return transformer.transform(url, type, encoding, data, status);
        }

        if (st != null) {
            return st.transform(url, type, encoding, data, status);
        }

    } else if (file != null) {

        if (type.equals(File.class)) {
            return (T) file;
        }

        if (type.equals(XmlDom.class)) {

            XmlDom result = null;

            try {
                FileInputStream fis = new FileInputStream(file);
                result = new XmlDom(fis);
                status.closeLater(fis);
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }

            return (T) result;
        }

        if (type.equals(XmlPullParser.class)) {

            XmlPullParser parser = Xml.newPullParser();
            try {

                FileInputStream fis = new FileInputStream(file);
                parser.setInput(fis, encoding);
                status.closeLater(fis);
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }
            return (T) parser;
        }

        if (type.equals(InputStream.class)) {
            try {
                FileInputStream fis = new FileInputStream(file);
                status.closeLater(fis);
                return (T) fis;
            } catch (Exception e) {
                AQUtility.report(e);
                return null;
            }
        }

    }

    return null;
}

From source file:com.android.browser.BookmarksPageCallbacks.java

private void editBookmark(BrowserBookmarksAdapter adapter, int position) {
    Intent intent = new Intent(getActivity(), AddBookmarkPage.class);
    Cursor cursor = adapter.getItem(position);
    Bundle item = new Bundle();
    item.putString(BrowserContract.Bookmarks.TITLE, cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE));
    item.putString(BrowserContract.Bookmarks.URL, cursor.getString(BookmarksLoader.COLUMN_INDEX_URL));
    byte[] data = cursor.getBlob(BookmarksLoader.COLUMN_INDEX_FAVICON);
    if (data != null) {
        item.putParcelable(BrowserContract.Bookmarks.FAVICON,
                BitmapFactory.decodeByteArray(data, 0, data.length));
    }//from   w  ww .  j av a  2  s  .c  o  m
    item.putLong(BrowserContract.Bookmarks._ID, cursor.getLong(BookmarksLoader.COLUMN_INDEX_ID));
    item.putLong(BrowserContract.Bookmarks.PARENT, cursor.getLong(BookmarksLoader.COLUMN_INDEX_PARENT));
    intent.putExtra(AddBookmarkPage.EXTRA_EDIT_BOOKMARK, item);
    intent.putExtra(AddBookmarkPage.EXTRA_IS_FOLDER,
            cursor.getInt(BookmarksLoader.COLUMN_INDEX_IS_FOLDER) == 1);
    startActivity(intent);
}

From source file:com.mobicage.rogerthat.plugins.friends.ServiceActionMenuActivity.java

private void populateScreen(final ServiceMenu menu) {
    menuBrandingHash = menu.branding;/* w  w  w. j av  a 2s .com*/
    final FriendsPlugin friendsPlugin = mService.getPlugin(FriendsPlugin.class);
    final MessagingPlugin messagingPlugin = mService.getPlugin(MessagingPlugin.class);
    final FriendStore store = friendsPlugin.getStore();

    List<Cell> usedCells = new ArrayList<Cell>();
    if (page == 0) {
        addAboutHandler(usedCells, menu.aboutLabel);
        addHistoryHandler(usedCells, store, menu.messagesLabel);
        addCallHandler(menu, usedCells, menu.callLabel);
        if (CloudConstants.isYSAAA()) {
            addScanHandler(menu, usedCells, null);
        } else {
            addShareHandler(menu, usedCells, menu.shareLabel);
        }
    }
    boolean[] rows = new boolean[] { false, false, false };
    if (page == 0)
        rows[0] = true;
    for (final ServiceMenuItem item : menu.itemList) {
        rows[(int) item.coords[1]] = true;
        final Cell cell = cells[(int) item.coords[0]][(int) item.coords[1]];
        View.OnClickListener onClickListener = new SafeViewOnClickListener() {
            @Override
            public void safeOnClick(View v) {
                pressMenuItem(menu, messagingPlugin, store, item);
            }
        };
        ((View) cell.icon.getParent()).setOnClickListener(onClickListener);
        cell.icon.setImageBitmap(BitmapFactory.decodeByteArray(item.icon, 0, item.icon.length));
        cell.icon.setVisibility(View.VISIBLE);
        cell.label.setText(item.label);
        cell.label.setVisibility(View.VISIBLE);
        usedCells.add(cell);
    }
    for (int i = 2; i >= 0; i--) {
        if (rows[i])
            break;
        tableRows[i].setVisibility(View.GONE);
    }
    boolean showBranded = false;
    boolean useDarkScheme = false;
    Integer menuItemColor = null;
    if (menu.branding != null) {
        try {
            BrandingMgr brandingMgr = messagingPlugin.getBrandingMgr();
            Friend friend = store.getExistingFriend(email);
            if (brandingMgr.isBrandingAvailable(menu.branding)) {
                BrandingResult br = brandingMgr.prepareBranding(menu.branding, friend, false);
                WebSettings settings = branding.getSettings();
                settings.setJavaScriptEnabled(false);
                settings.setBlockNetworkImage(false);
                branding.setVisibility(View.VISIBLE);
                branding.setVerticalScrollBarEnabled(false);

                final int displayWidth = UIUtils.getDisplayWidth(this);
                final int calculatedHeight = BrandingMgr.calculateHeight(br, displayWidth);
                final long start = System.currentTimeMillis();
                branding.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        int height = branding.getMeasuredHeight();
                        if (height > calculatedHeight * 90 / 100 || System.currentTimeMillis() - start > 3000) {
                            if (calculatedHeight > 0) {
                                setBrandingHeight(height);
                            } else {
                                mService.postDelayedOnUIHandler(new SafeRunnable() {
                                    @Override
                                    protected void safeRun() throws Exception {
                                        setBrandingHeight(branding.getMeasuredHeight());
                                    }
                                }, 100);
                            }
                            branding.getViewTreeObserver().removeOnPreDrawListener(this);
                        }
                        return false;
                    }
                });
                branding.loadUrl("file://" + br.file.getAbsolutePath());

                if (br.color != null) {
                    branding.setBackgroundColor(br.color);
                    activity.setBackgroundColor(br.color);
                }
                if (br.scheme == ColorScheme.dark) {
                    for (Cell cell : usedCells) {
                        cell.label.setTextColor(darkSchemeTextColor);
                        cell.label.setShadowLayer(2, 1, 1, Color.BLACK);
                    }
                    useDarkScheme = true;
                }
                menuItemColor = br.menuItemColor;

                final ImageView watermarkView = (ImageView) findViewById(R.id.watermark);
                if (br.watermark != null) {
                    BitmapDrawable watermark = new BitmapDrawable(getResources(),
                            BitmapFactory.decodeFile(br.watermark.getAbsolutePath()));
                    watermark.setGravity(Gravity.BOTTOM | Gravity.RIGHT);

                    watermarkView.setImageDrawable(watermark);
                    final LayoutParams layoutParams = watermarkView.getLayoutParams();
                    layoutParams.width = layoutParams.height = displayWidth;
                } else {
                    watermarkView.setImageDrawable(null);
                }

                showBranded = true;
            } else {
                friend.actionMenu = menu;
                friend.actionMenu.items = menu.itemList.toArray(new ServiceMenuItemTO[] {});
                brandingMgr.queue(friend);
            }
        } catch (BrandingFailureException e) {
            L.bug("Could not display service action menu with branding.", e);
        }
    }
    if (!showBranded) {
        setNavigationBarVisible(AppConstants.SHOW_NAV_HEADER);
        setNavigationBarTitle(menu.name);
        title.setVisibility(View.GONE);
        title.setText(menu.name);
    }

    for (final Cell cell : usedCells) {
        final View p = (View) cell.icon.getParent();
        final Drawable d = getResources().getDrawable(
                useDarkScheme ? R.drawable.mc_smi_background_light : R.drawable.mc_smi_background_dark);
        p.setBackgroundDrawable(d);
    }

    if (menuItemColor == null)
        menuItemColor = Color.parseColor("#646464");

    for (Cell cell : new Cell[] { cells[0][0], cells[1][0], cells[2][0], cells[3][0] })
        cell.faIcon.setTextColor(menuItemColor);

    if (menu.maxPage > 0) {
        for (int i = 0; i <= menu.maxPage; i++) {
            ImageView bolleke = (ImageView) getLayoutInflater().inflate(R.layout.page, pages, false);
            if (page == i) {
                if (useDarkScheme) {
                    bolleke.setImageResource(R.drawable.current_page_dark);
                } else {
                    bolleke.setImageResource(R.drawable.current_page_light);
                }
            } else {
                if (useDarkScheme) {
                    bolleke.setImageResource(R.drawable.other_page_dark);
                } else {
                    bolleke.setImageResource(R.drawable.other_page_light);
                }
            }
            pages.addView(bolleke);
        }
        pages.setVisibility(View.VISIBLE);
    }
    final int leftPage = page - 1;
    final int rightPage = page + 1;
    final String service = email;
    Slider instance = new Slider(this, this, page == menu.maxPage ? null : new Slider.Swiper() {
        @Override
        public Intent onSwipe() {
            return new Intent(ServiceActionMenuActivity.this, ServiceActionMenuActivity.class)
                    .putExtra(SERVICE_EMAIL, service).putExtra(MENU_PAGE, rightPage);
        }
    }, page == 0 ? null : new Slider.Swiper() {
        @Override
        public Intent onSwipe() {
            return new Intent(ServiceActionMenuActivity.this, ServiceActionMenuActivity.class)
                    .putExtra(SERVICE_EMAIL, service).putExtra(MENU_PAGE, leftPage);
        }
    });
    mGestureScanner = new GestureDetector(this, instance);
}

From source file:LPGoogleFunctions.LPGoogleFunctions.java

/**
 * The Google Maps Image APIs make it easy to embed a street view image into your image view.
 * @param location - The location (such as 40.457375,-80.009353).
 * @param imageWidth - Specifies width size of the image in pixels.
 * @param imageHeight - Specifies height size of the image in pixels.
 * @param heading - Indicates the compass heading of the camera. Accepted values are from 0 to 360 (both values indicating North, with 90 indicating East, and 180 South). 
 * If no heading is specified, a value will be calculated that directs the camera towards the specified location, from the point at which the closest photograph was taken.
 * @param fov - Determines the horizontal field of view of the image. The field of view is expressed in degrees, with a maximum allowed value of 120.
 * When dealing with a fixed-size viewport, as with a Street View image of a set size, field of view in essence represents zoom, with smaller numbers indicating a higher level of zoom.
 * @param pitch- Specifies the up or down angle of the camera relative to the Street View vehicle. This is often, but not always, flat horizontal.
 * Positive values angle the camera up (with 90 degrees indicating straight up).
 * Negative values angle the camera down (with -90 indicating straight down).
 * @param responseHandler//from   w ww .ja  v  a2 s .c o m
 * @Override public void willLoadStreetViewImage();
 * @Override public void didLoadStreetViewImage(Bitmap bmp)
 * @Override public void errorLoadingStreetViewImage(Throwable error);
 */

public void loadStreetViewImageForLocation(LPLocation location, int imageWidth, int imageHeight, float heading,
        float fov, float pitch, final StreetViewImageListener responseHandler) {
    if (responseHandler != null)
        responseHandler.willLoadStreetViewImage();

    RequestParams parameters = new RequestParams();

    DecimalFormatSymbols separator = new DecimalFormatSymbols();
    separator.setDecimalSeparator('.');
    DecimalFormat coordinateDecimalFormat = new DecimalFormat("##.######");
    coordinateDecimalFormat.setDecimalFormatSymbols(separator);

    DecimalFormat twoDecimalFormat = new DecimalFormat(".##");
    twoDecimalFormat.setDecimalFormatSymbols(separator);

    parameters.put("key", this.googleAPIBrowserKey);
    parameters.put("sensor", sensor ? "true" : "false");
    parameters.put("size", String.format("%dx%d", imageWidth, imageHeight));
    if (location != null)
        parameters.put("location", String.format("%s,%s", coordinateDecimalFormat.format(location.latitude),
                coordinateDecimalFormat.format(location.longitude)));
    parameters.put("heading", twoDecimalFormat.format(heading));
    parameters.put("fov", twoDecimalFormat.format(fov));
    parameters.put("pitch", twoDecimalFormat.format(pitch));

    this.client.get(googleAPIStreetViewImageURL, parameters, new BinaryHttpResponseHandler() {
        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            if (responseHandler != null)
                responseHandler.errorLoadingStreetViewImage(arg3);
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                Bitmap bmp = BitmapFactory.decodeByteArray(arg2, 0, arg2.length);

                if (responseHandler != null)
                    responseHandler.didLoadStreetViewImage(bmp);
            } catch (Exception e) {
                e.printStackTrace();

                if (responseHandler != null)
                    responseHandler.errorLoadingStreetViewImage(e.getCause());
            }
        }
    });
}

From source file:com.binaryelysium.mp3tunes.api.Locker.java

public Bitmap getAlbumArtFromFileKey(String key)
        throws InvalidSessionException, LockerException, LoginException {
    RemoteMethod method = new RemoteMethod.Builder(RemoteMethod.METHODS.ALBUM_ART_GET).addFileKey(key).create();
    try {/*w  w  w. j  a v  a 2 s.  com*/
        byte[] data = HttpClientCaller.getInstance().callBytes(method);
        Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
        return bm;
    } catch (IOException e) {
        throw new LockerException("download failed");
    }
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 *            Categories : Insert categories or update categories table
 *   /*  w w  w.  ja  v  a  2s.com*/
 * @return number of downloaded bytes 
 */
public int addUpdCateg(Context ctx) {

    int bdown = 0;

    String response = Download_Data.Download_Categories();

    if (response != null)
        bdown += response.length();

    try {
        JSONArray jArrCategs = new JSONArray(response);
        int NCateg = jArrCategs.length();

        if (!db.isOpen())
            db = this.getWritableDatabase();

        //--------- Create Helpers for Local db -----------------
        final InsertHelper iHelpC = new InsertHelper(db, TABLE_Categories);

        int c1 = iHelpC.getColumnIndex(KEY_CatID);
        int c2 = iHelpC.getColumnIndex(KEY_CatName);
        int c3 = iHelpC.getColumnIndex(KEY_CatIcon);
        int c4 = iHelpC.getColumnIndex(KEY_CatLevel);
        int c5 = iHelpC.getColumnIndex(KEY_CatParentID);
        int c6 = iHelpC.getColumnIndex(KEY_CatVisible);

        try {
            db.beginTransaction();
            Log.e("UPD", "Categs");
            for (int i = 0; i < NCateg; i++) {

                float prog = 100 * ((float) (i + 1)) / ((float) NCateg);

                ctx.sendBroadcast(
                        new Intent("android.intent.action.MAIN").putExtra("progressval", (int) (prog * 0.67)));

                JSONArray jArrData = new JSONArray(jArrCategs.get(i).toString());

                int CategID = jArrData.getInt(0);
                String CategName = jArrData.getString(1);
                int CategLevel = jArrData.getInt(2);
                int CategParentId = jArrData.getInt(3);
                String CategParams = jArrData.getString(4);

                JSONObject cpOb = new JSONObject(CategParams);
                String CategIconPath = cpOb.getString("image");

                String fullPath = Constants_API.COM_Protocol + Constants_API.ServerSTR
                        + Constants_API.remoteImages + CategIconPath;

                // Download icon
                byte[] CategIcon = Download_Data.Down_Image(fullPath);

                //------- Resize icon based on the device needs and store in db. --------------------
                Bitmap CategIconBM = BitmapFactory.decodeByteArray(CategIcon, 0, CategIcon.length);
                CategIconBM = Bitmap.createScaledBitmap(CategIconBM,
                        (int) ((float) Fragment_Map.metrics.densityDpi / 4.5),
                        (int) ((float) Fragment_Map.metrics.densityDpi / 4), true);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                CategIconBM.compress(Bitmap.CompressFormat.PNG, 100, stream);
                CategIcon = stream.toByteArray();
                //---------------------------------------------------------

                bdown += CategIcon.length;

                // Local db
                Cursor cursorC = db.rawQuery("SELECT " + KEY_CatID + "," + KEY_CatVisible + " FROM "
                        + TABLE_Categories + " WHERE " + KEY_CatID + "=" + Integer.toString(CategID), null);

                if (cursorC.moveToFirst()) { // Update 
                    iHelpC.prepareForReplace();
                    iHelpC.bind(c6, cursorC.getInt(1) == 1);
                } else {
                    iHelpC.prepareForInsert();
                    iHelpC.bind(c6, 1); // Insert
                }

                iHelpC.bind(c1, CategID);
                iHelpC.bind(c2, CategName);
                iHelpC.bind(c3, CategIcon);
                iHelpC.bind(c4, CategLevel);
                iHelpC.bind(c5, CategParentId);
                cursorC.close();

                iHelpC.execute();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        } // TRY OF TRANSACTION 
    } catch (JSONException e1) {
        e1.printStackTrace();
        Log.e(Constants_API.TAG, TAG_Class + ": Categories update failed");
    } // TRY OF JSONARRAY

    return bdown;
}

From source file:keyboard.ecloga.com.eclogakeyboard.EclogaKeyboard.java

@Override
public void onStartInputView(EditorInfo info, boolean restarting) {
    initializeKeyboard();/*from  ww w  .  j  a  v a2s. c om*/
    onRotate();

    if (mVoiceRecognitionTrigger != null) {
        mVoiceRecognitionTrigger.onStartInputView();
    }

    vbListenerPause = false;

    if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("random")) {
        Random rand = new Random();

        int randInt = rand.nextInt(25);

        switch (randInt) {
        case 1:
            kv.setBackgroundColor(getResources().getColor(R.color.white));
            break;
        case 2:
            kv.setBackgroundColor(getResources().getColor(R.color.black));
            break;
        case 3:
            kv.setBackgroundColor(getResources().getColor(R.color.purple));
            break;
        case 4:
            kv.setBackgroundColor(getResources().getColor(R.color.red));
            break;
        case 5:
            kv.setBackgroundColor(getResources().getColor(R.color.pink));
            break;
        case 6:
            kv.setBackgroundColor(getResources().getColor(R.color.blue));
            break;
        case 7:
            kv.setBackgroundColor(getResources().getColor(R.color.green));
            break;
        case 8:
            kv.setBackgroundColor(getResources().getColor(R.color.yellow));
            break;
        case 9:
            kv.setBackgroundColor(getResources().getColor(R.color.orange));
            break;
        case 10:
            kv.setBackgroundColor(getResources().getColor(R.color.grey));
            break;
        case 11:
            kv.setBackgroundColor(getResources().getColor(R.color.lightpurple));
            break;
        case 12:
            kv.setBackgroundColor(getResources().getColor(R.color.lightred));
            break;
        case 13:
            kv.setBackgroundColor(getResources().getColor(R.color.lightpink));
            break;
        case 14:
            kv.setBackgroundColor(getResources().getColor(R.color.lightblue));
            break;
        case 15:
            kv.setBackgroundColor(getResources().getColor(R.color.lightgreen));
            break;
        case 16:
            kv.setBackgroundColor(getResources().getColor(R.color.lightyellow));
            break;
        case 17:
            kv.setBackgroundColor(getResources().getColor(R.color.lightgrey));
            break;
        case 18:
            kv.setBackgroundColor(getResources().getColor(R.color.lightorange));
            break;
        case 19:
            kv.setBackgroundColor(getResources().getColor(R.color.darkpurple));
            break;
        case 20:
            kv.setBackgroundColor(getResources().getColor(R.color.darkorange));
            break;
        case 21:
            kv.setBackgroundColor(getResources().getColor(R.color.darkblue));
            break;
        case 22:
            kv.setBackgroundColor(getResources().getColor(R.color.darkgreen));
            break;
        case 23:
            kv.setBackgroundColor(getResources().getColor(R.color.darkred));
            break;
        case 24:
            kv.setBackgroundColor(getResources().getColor(R.color.darkyellow));
            break;
        case 25:
            kv.setBackgroundColor(getResources().getColor(R.color.darkpink));
            break;
        }
    }

    else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_1")) {
        kv.setBackgroundResource(R.drawable.pattern_1);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_2")) {
        kv.setBackgroundResource(R.drawable.pattern_2);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_3")) {
        kv.setBackgroundResource(R.drawable.pattern_3);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_4")) {
        kv.setBackgroundResource(R.drawable.pattern_4);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_5")) {
        kv.setBackgroundResource(R.drawable.pattern_5);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_6")) {
        kv.setBackgroundResource(R.drawable.pattern_6);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_7")) {
        kv.setBackgroundResource(R.drawable.pattern_7);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_8")) {
        kv.setBackgroundResource(R.drawable.pattern_8);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_9")) {
        kv.setBackgroundResource(R.drawable.pattern_9);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_10")) {
        kv.setBackgroundResource(R.drawable.pattern_10);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_11")) {
        kv.setBackgroundResource(R.drawable.pattern_11);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_12")) {
        kv.setBackgroundResource(R.drawable.pattern_12);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_13")) {
        kv.setBackgroundResource(R.drawable.pattern_13);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_14")) {
        kv.setBackgroundResource(R.drawable.pattern_14);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_15")) {
        kv.setBackgroundResource(R.drawable.pattern_15);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_16")) {
        kv.setBackgroundResource(R.drawable.pattern_16);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pattern_17")) {
        kv.setBackgroundResource(R.drawable.pattern_17);

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_1")) {
        kv.setBackgroundResource(R.drawable.nature_1);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_2")) {
        kv.setBackgroundResource(R.drawable.nature_2);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_3")) {
        kv.setBackgroundResource(R.drawable.nature_3);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_4")) {
        kv.setBackgroundResource(R.drawable.nature_4);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_5")) {
        kv.setBackgroundResource(R.drawable.nature_5);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_6")) {
        kv.setBackgroundResource(R.drawable.nature_6);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_7")) {
        kv.setBackgroundResource(R.drawable.nature_7);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_8")) {
        kv.setBackgroundResource(R.drawable.nature_8);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_9")) {
        kv.setBackgroundResource(R.drawable.nature_9);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_10")) {
        kv.setBackgroundResource(R.drawable.nature_10);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_11")) {
        kv.setBackgroundResource(R.drawable.nature_11);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_12")) {
        kv.setBackgroundResource(R.drawable.nature_12);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_13")) {
        kv.setBackgroundResource(R.drawable.nature_13);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("nature_14")) {
        kv.setBackgroundResource(R.drawable.nature_14);

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("black")) {
        kv.setBackgroundColor(getResources().getColor(R.color.black));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("white")) {
        kv.setBackgroundColor(getResources().getColor(R.color.white));

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("transparent")) {
        kv.setBackgroundColor(getResources().getColor(R.color.transparent));

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_1")) {
        kv.setBackgroundResource(R.drawable.gradient_1);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_2")) {
        kv.setBackgroundResource(R.drawable.gradient_2);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_3")) {
        kv.setBackgroundResource(R.drawable.gradient_3);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_4")) {
        kv.setBackgroundResource(R.drawable.gradient_4);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_5")) {
        kv.setBackgroundResource(R.drawable.gradient_5);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_6")) {
        kv.setBackgroundResource(R.drawable.gradient_6);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_7")) {
        kv.setBackgroundResource(R.drawable.gradient_7);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_8")) {
        kv.setBackgroundResource(R.drawable.gradient_8);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_9")) {
        kv.setBackgroundResource(R.drawable.gradient_9);
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("gradient_10")) {
        kv.setBackgroundResource(R.drawable.gradient_10);

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("red")) {
        kv.setBackgroundColor(getResources().getColor(R.color.red));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("pink")) {
        kv.setBackgroundColor(getResources().getColor(R.color.pink));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("purple")) {
        kv.setBackgroundColor(getResources().getColor(R.color.purple));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("blue")) {
        kv.setBackgroundColor(getResources().getColor(R.color.blue));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("green")) {
        kv.setBackgroundColor(getResources().getColor(R.color.green));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("yellow")) {
        kv.setBackgroundColor(getResources().getColor(R.color.yellow));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("orange")) {
        kv.setBackgroundColor(getResources().getColor(R.color.orange));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("grey")) {
        kv.setBackgroundColor(getResources().getColor(R.color.grey));

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightred")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightred));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightpink")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightpink));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightpurple")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightpurple));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightblue")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightblue));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightgreen")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightgreen));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightyellow")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightyellow));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightorange")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightorange));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("lightgrey")) {
        kv.setBackgroundColor(getResources().getColor(R.color.lightgrey));

    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkred")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkred));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkpink")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkpink));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkpurple")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkpurple));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkblue")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkblue));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkgreen")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkgreen));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkyellow")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkyellow));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkorange")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkorange));
    } else if (Preferences.getDefaults("bgcolor", getApplicationContext()).equals("darkgrey")) {
        kv.setBackgroundColor(getResources().getColor(R.color.darkgrey));
    } else {
        String uploadString = Preferences.getDefaults("bgcolor", getApplicationContext());

        byte[] decodedString = Base64.decode(uploadString, Base64.URL_SAFE);
        Bitmap photo = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        BitmapDrawable bdrawable = new BitmapDrawable(getApplication().getResources(), photo);
        kv.setBackgroundDrawable(bdrawable);
    }

    if (Preferences.getDefaults("autocapitalize", getApplicationContext()).equals("true")) {
        autoCapitalize = true;
    } else if (Preferences.getDefaults("autocapitalize", getApplicationContext()).equals("false")) {
        autoCapitalize = false;
    }

    if (Preferences.getDefaults("volumebuttons", getApplicationContext()).equals("true")) {
        volumeButtons = true;
    } else if (Preferences.getDefaults("volumebuttons", getApplicationContext()).equals("false")) {
        volumeButtons = false;
    }

    if (Preferences.getDefaults("allcaps", getApplicationContext()).equals("true")) {
        allCaps = true;
    } else if (Preferences.getDefaults("allcaps", getApplicationContext()).equals("false")) {
        allCaps = false;
    }

    if (Preferences.getDefaults("autospacing", getApplicationContext()).equals("true")) {
        autoSpacing = true;
    } else if (Preferences.getDefaults("autospacing", getApplicationContext()).equals("false")) {
        autoSpacing = false;
    }

    if (Preferences.getDefaults("changekeyboard", getApplicationContext()).equals("true")) {
        changeKeyboard = true;
    } else if (Preferences.getDefaults("changekeyboard", getApplicationContext()).equals("false")) {
        changeKeyboard = false;
    }

    if (Preferences.getDefaults("shakedelete", getApplicationContext()).equals("true")) {
        shakeDelete = true;
    } else if (Preferences.getDefaults("shakedelete", getApplicationContext()).equals("false")) {
        shakeDelete = false;
    }

    if (Preferences.getDefaults("doublespace", getApplicationContext()).equals("true")) {
        spaceDot = true;
    } else if (Preferences.getDefaults("doublespace", getApplicationContext()).equals("false")) {
        spaceDot = false;
    }

    if (Preferences.getDefaults("voiceinput", getApplicationContext()).equals("true")) {
        voiceInput = true;
    } else if (Preferences.getDefaults("voiceinout", getApplicationContext()).equals("false")) {
        voiceInput = false;
    }

    if (Preferences.getDefaults("popup", getApplicationContext()).equals("true")) {
        popupKeypress = true;
    } else if (Preferences.getDefaults("popup", getApplicationContext()).equals("false")) {
        popupKeypress = false;
    }

    if (Preferences.getDefaults("oppositecase", getApplicationContext()).equals("true")) {
        oppositeCase = true;
    } else if (Preferences.getDefaults("oppositecase", getApplicationContext()).equals("false")) {
        oppositeCase = false;
    }

    if (changeKeyboard) {
        MovementDetector.getInstance(getApplicationContext()).start();

        MovementDetector.getInstance(getApplicationContext()).addListener(new MovementDetector.Listener() {

            @Override
            public void onMotionDetected(SensorEvent event, float acceleration) {
                if (MovementDetector.direction[1].equals("LEFT")) {
                    playSwipeH();
                    onSwipeLeft();
                } else if (MovementDetector.direction[1].equals("RIGHT")) {
                    playSwipeH();
                    onSwipeRight();
                }

                if (MovementDetector.direction[0].equals("UP")) {
                    playSwipeV();
                    onSwipeUp();
                } else if (MovementDetector.direction[0].equals("DOWN")) {
                    playSwipeV();
                    onSwipeDown();
                }
            }
        });
    }

    keypresscounter1 = Preferences.getDefaults("keypresscounter1", getApplicationContext());
    keypresscounter2 = Preferences.getDefaults("keypresscounter2", getApplicationContext());
    keypresscounter3 = Preferences.getDefaults("keypresscounter3", getApplicationContext());

    keyPressCounter = Integer.parseInt(Preferences.getDefaults("keypresses", getApplicationContext()));

    time1 = Preferences.getDefaults("time1", getApplicationContext());
    time2 = Preferences.getDefaults("time2", getApplicationContext());
    time3 = Preferences.getDefaults("time3", getApplicationContext());

    time = Integer.parseInt(Preferences.getDefaults("time", getApplicationContext()));

    tTime = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            time = time + 1;

            if (time > 300 && time <= 960 && time1.equals("false")) {
                NotificationManager notif = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.notify, "Ecloga Keyboard",
                        System.currentTimeMillis());
                PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0,
                        new Intent(getApplicationContext(), Home.class), 0);

                notify.setLatestEventInfo(getApplicationContext(), "Warming up!", "Type more than 360 seconds",
                        pending);
                notif.notify(0, notify);

                Preferences.setDefaults("time1", "true", getApplicationContext());
            } else if (time > 960 && time <= 3600 && time2.equals("false")) {
                NotificationManager notif = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.notify, "Ecloga Keyboard",
                        System.currentTimeMillis());
                PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0,
                        new Intent(getApplicationContext(), Home.class), 0);

                notify.setLatestEventInfo(getApplicationContext(), "Keep it up!", "Type more than 960 seconds",
                        pending);
                notif.notify(0, notify);

                Preferences.setDefaults("time2", "true", getApplicationContext());
            } else if (time > 3600 && time3.equals("false")) {
                NotificationManager notif = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.notify, "Ecloga Keyboard",
                        System.currentTimeMillis());
                PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0,
                        new Intent(getApplicationContext(), Home.class), 0);

                notify.setLatestEventInfo(getApplicationContext(), "Typing master!",
                        "Type more than 3600 seconds", pending);
                notif.notify(0, notify);

                Preferences.setDefaults("time3", "true", getApplicationContext());
            }

            Preferences.setDefaults("time", String.valueOf(time), getApplicationContext());
        }

        @Override
        public void onFinish() {
            tTime.start();
        }
    }.start();

    if (popupKeypress) {
        kv.setPreviewEnabled(true);
    } else {
        kv.setPreviewEnabled(false);
    }

    if (shakeDelete) {
        mShaker = new ShakeListener(this);
        mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
            public void onShake() {
                InputConnection ic = getCurrentInputConnection();
                ic.deleteSurroundingText(500, 500);
            }
        });
    }

    super.onStartInputView(info, restarting);
}