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:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java

public void render(Context context, ViewGroup frame, Obj obj, boolean allowInteractions) {
    JSONObject content = obj.getJson();/* w w  w .j  a v  a2 s.co m*/
    byte[] raw = obj.getRaw();
    if (raw == null) {
        Pair<JSONObject, byte[]> p = splitRaw(content);
        content = p.first;
        raw = p.second;
    }
    ImageView imageView = new ImageView(context);
    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    imageView.setImageBitmap(BitmapFactory.decodeByteArray(raw, 0, raw.length));
    //        App.instance().objectImages.lazyLoadImage(raw.hashCode(), raw, imageView);
    frame.addView(imageView);
}

From source file:com.ddoskify.CameraOverlayActivity.java

/**
 * Initializes the UI and initiates the creation of a face detector.
 *//*ww w  .j  a v  a 2s  .  c  om*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
    mFaces = new ArrayList<FaceTracker>();

    final ImageButton button = (ImageButton) findViewById(R.id.flipButton);
    button.setOnClickListener(mFlipButtonListener);

    if (savedInstanceState != null) {
        mIsFrontFacing = savedInstanceState.getBoolean("IsFrontFacing");
    }

    mTakePictureButton = (Button) findViewById(R.id.takePictureButton);
    mTakePictureButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.e("CameraOverlay", "Button has been pressed");
            mCameraSource.takePicture(new CameraSource.ShutterCallback() {
                @Override
                public void onShutter() {
                    //                        mCameraSource.stop();
                    Snackbar.make(findViewById(android.R.id.content), "Picture Taken!", Snackbar.LENGTH_SHORT)
                            .setActionTextColor(Color.BLACK).show();
                }
            }, new CameraSource.PictureCallback() {
                public void onPictureTaken(byte[] data) {
                    int re = ActivityCompat.checkSelfPermission(getApplicationContext(),
                            Manifest.permission.WRITE_EXTERNAL_STORAGE);

                    if (!isStorageAllowed()) {
                        requestStoragePermission();
                    }

                    File pictureFile = getOutputMediaFile();
                    if (pictureFile == null) {
                        return;
                    }
                    try {

                        Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
                        Bitmap resizedBitmap = Bitmap.createBitmap(mGraphicOverlay.getWidth(),
                                mGraphicOverlay.getHeight(), picture.getConfig());
                        Canvas canvas = new Canvas(resizedBitmap);

                        Matrix matrix = new Matrix();

                        matrix.setScale((float) resizedBitmap.getWidth() / (float) picture.getWidth(),
                                (float) resizedBitmap.getHeight() / (float) picture.getHeight());

                        if (mIsFrontFacing) {
                            // mirror by inverting scale and translating
                            matrix.preScale(-1, 1);
                            matrix.postTranslate(canvas.getWidth(), 0);
                        }
                        Paint paint = new Paint();
                        canvas.drawBitmap(picture, matrix, paint);

                        mGraphicOverlay.draw(canvas); // make those accessible

                        FileOutputStream fos = new FileOutputStream(pictureFile);
                        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                        fos.close();

                        Intent intent = new Intent(getApplicationContext(), PhotoReviewActivity.class);
                        intent.putExtra(BITMAP_MESSAGE, pictureFile.toString());
                        startActivity(intent);
                        Log.d("CameraOverlay", "Starting PhotoReviewActivity " + pictureFile.toString());

                    } catch (FileNotFoundException e) {
                        Log.e("CameraOverlay", e.toString());
                    } catch (IOException e) {
                        Log.e("CameraOverlay", e.toString());
                    }
                }
            });
        }
    });

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource();
    } else {
        requestCameraPermission();
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {//w  w w . j  a  va2  s  .co m
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "")
                .replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);

        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }

        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {// w ww  .j  av a2  s  . c  o  m
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:ca.ualberta.trinkettrader.Inventory.Trinket.Pictures.Picture.java

/**
 * Returns a bitmap representation of the picture. This should be used
 * anytime the image needs to be displayed. Note that a dummy bitmap will
 * be generated if the image is not yet loaded.
 *
 * @return bitmap representation of the picture
 *//*  w  w w. ja  v a2 s .c  o m*/
public Bitmap getBitmap() {
    return BitmapFactory.decodeByteArray(pictureByteArray, 0, pictureByteArray.length);
}

From source file:co.nerdart.ourss.adapter.FeedsCursorAdapter.java

@Override
protected void bindChildView(View view, Context context, Cursor cursor) {
    view.findViewById(R.id.indicator).setVisibility(View.INVISIBLE);

    TextView textView = ((TextView) view.findViewById(android.R.id.text1));
    long feedId = cursor.getLong(idPosition);
    if (feedId == mSelectedFeedId) {
        view.setBackgroundResource(android.R.color.holo_blue_dark);
    } else {//w  w  w.ja  v a 2 s .com
        view.setBackgroundResource(android.R.color.transparent);
    }

    TextView updateTextView = ((TextView) view.findViewById(android.R.id.text2));
    updateTextView.setVisibility(View.VISIBLE);

    if (cursor.isNull(errorPosition)) {
        long timestamp = cursor.getLong(lastUpdateColumn);

        // Date formatting is expensive, look at the cache
        String formattedDate = mFormattedDateCache.get(timestamp);
        if (formattedDate == null) {
            Date date = new Date(timestamp);

            formattedDate = context.getString(R.string.update) + COLON
                    + (timestamp == 0 ? context.getString(R.string.never)
                            : new StringBuilder(Constants.DATE_FORMAT.format(date)).append(' ')
                                    .append(Constants.TIME_FORMAT.format(date)));
            mFormattedDateCache.put(timestamp, formattedDate);
        }

        updateTextView.setText(formattedDate);
    } else {
        updateTextView.setText(new StringBuilder(context.getString(R.string.error)).append(COLON)
                .append(cursor.getString(errorPosition)));
    }

    byte[] iconBytes = cursor.getBlob(iconPosition);

    if (iconBytes != null && iconBytes.length > 0) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);

        if (bitmap != null && bitmap.getHeight() > 0 && bitmap.getWidth() > 0) {
            int bitmapSizeInDip = UiUtils.dpToPixel(18);

            if (bitmap.getHeight() != bitmapSizeInDip) {
                bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
            }
            textView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(context.getResources(), bitmap),
                    null, null, null);
        } else {
            textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    } else {
        view.setTag(null);
        textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
    }

    int unreadCount;
    synchronized (mUnreadItemsByFeed) {
        unreadCount = mUnreadItemsByFeed.get(feedId);
    }

    if (unreadCount > 0) {
        textView.setEnabled(true);
        updateTextView.setEnabled(true);
    } else {
        textView.setEnabled(false);
        updateTextView.setEnabled(false);
    }
    textView.setText(
            (cursor.isNull(namePosition) ? cursor.getString(linkPosition) : cursor.getString(namePosition))
                    + (unreadCount > 0 ? " (" + unreadCount + ")" : ""));

    View sortView = view.findViewById(R.id.sortitem);
    if (!sortViews.contains(sortView)) { // as we are reusing views, this is fine
        sortViews.add(sortView);
    }
    sortView.setVisibility(feedSort ? View.VISIBLE : View.GONE);
}

From source file:br.com.GUI.perfil.PerfilAluno.java

public void refresh() {

    Aluno a = new Aluno();

    a = new Aluno().buscarAlunoEspecificoWeb(pref.getString("usuario", null));

    Log.i("user no shared pref", pref.getString("usuario", null));
    try {/*from  w  w w  .  j  a v  a  2s  . c  o  m*/
        byte[] foto = a.buscarFotoAluno(b, a.getUsuario());
        bmp = BitmapFactory.decodeByteArray(foto, 0, foto.length);
        img.setImageBitmap(bmp);
    } catch (Exception ex) {
        img.setImageDrawable(getResources().getDrawable(R.drawable.profile));
    }

    nome.setText(a.getNome());
    if (nome.getText().toString().equals("anyType{}")) {
        nome.setText("");
    }
    try {
        if (!a.getDataDeNascimento().equals("anyType{}") && a.getDataDeNascimento() != null) {
            String dia = a.getDataDeNascimento().substring(0, a.getDataDeNascimento().indexOf("/"));
            String mes = a.getDataDeNascimento().substring(a.getDataDeNascimento().indexOf("/") + 1,
                    a.getDataDeNascimento().lastIndexOf("/"));
            String ano = a.getDataDeNascimento().substring(a.getDataDeNascimento().lastIndexOf("/") + 1);

            dataNascimentoDia.setValue(Integer.parseInt(dia));
            dataNascimentoMes.setValue(Integer.parseInt(mes));
            dataNascimentoAno.setValue(Integer.parseInt(ano));
        }
    } catch (Exception e) {
        dataNascimentoDia.setValue(1);
        dataNascimentoMes.setValue(1);
        dataNascimentoAno.setValue(1900);
    }

    telefone.setText(a.getTelefone());
    if (telefone.getText().toString().equals("anyType{}")) {
        telefone.setText("");
    }
    email.setText(a.getEmail());
    if (email.getText().toString().equals("anyType{}")) {
        email.setText("");
    }

}

From source file:com.webXells.ImageResizer.ImageResizePlugin.java

private Bitmap getBitmap(String imageData, String imageDataType) throws IOException {
    Bitmap bmp;//  w w  w  .j a va 2  s.co m
    if (imageDataType.equals(IMAGE_DATA_TYPE_BASE64)) {
        byte[] blob = Base64.decode(imageData, Base64.DEFAULT);
        bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
    } else {
        File imagefile = new File(imageData);
        FileInputStream fis = new FileInputStream(imagefile);
        bmp = BitmapFactory.decodeStream(fis);
    }
    return bmp;
}

From source file:mobisocial.bento.todo.io.BentoManager.java

synchronized public Bitmap getTodoBitmap(Uri objUri, String todoUuid, int targetWidth, int targetHeight,
        float degrees) {
    Bitmap bitmap = null;/*w  ww  .  jav  a  2s .  co  m*/

    DbFeed dbFeed = mMusubi.objForUri(objUri).getSubfeed();

    Cursor c = dbFeed.query();
    c.moveToFirst();
    for (int i = 0; i < c.getCount(); i++) {
        Obj object = mMusubi.objForCursor(c);
        if (object != null && object.getJson() != null && object.getJson().has(TODO_IMAGE)) {
            JSONObject diff = object.getJson().optJSONObject(TODO_IMAGE);
            if (todoUuid.equals(diff.optString(TODO_IMAGE_UUID))) {
                byte[] byteArray = Base64.decode(object.getJson().optString(B64JPGTHUMB), Base64.DEFAULT);
                bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                break;
            }
        }
        c.moveToNext();
    }
    c.close();

    if (bitmap != null) {
        bitmap = BitmapHelper.getResizedBitmap(bitmap, targetWidth, targetHeight, degrees);
    }

    return bitmap;
}

From source file:com.amrutpatil.makeanote.NotesActivity.java

@Override
public void onLoadFinished(Loader<List<Note>> loader, List<Note> data) {
    this.mNotes = data;
    //Retrieve the image from local storage/Google Drive/Dropbox in a separate thread
    Thread[] threads = new Thread[mNotes.size()];
    int threadCounter = 0;

    for (final Note aNote : mNotes) {
        //If the note is coming from Google Drive
        if (AppConstant.GOOGLE_DRIVE_SELECTION == aNote.getStorageSelection()) {
            GDUT.init(getApplicationContext());
            //Check if Google Drive is accessible and if the user account has been logged in successfully
            if (checkPlayServices() && checkUserAccount()) {
                GDActions.init(this, GDUT.AM.getActiveEmil());
                GDActions.connect(true);
            }/*from   w  w  w .  ja  va2s . co m*/

            threads[threadCounter] = new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        //Get the image file
                        ArrayList<GDActions.GF> gfs = GDActions.search(
                                AppSharedPreferences.getGoogleDriveResourceId(getApplicationContext()),
                                aNote.getImagePath(), GDUT.MIME_JPEG);

                        if (gfs.size() > 0) {
                            //Retrieve the file, convert it into Bitmap to display on the screen
                            byte[] imageBytes = GDActions.read(gfs.get(0).id, 0);

                            //Process the entire byte array and convert it into an image
                            Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                            aNote.setBitmap(bitmap);
                            mIsImageNotFound = false;
                            mNotesAdapter.setData(mNotes);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //Tell the Adapter that a graphic image has been obtained
                                    mNotesAdapter.notifyImageObtained();
                                }
                            });
                        } else {
                            aNote.setBitmap(
                                    BitmapFactory.decodeResource(getResources(), R.drawable.ic_loading));
                            mIsImageNotFound = true;
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } while (mIsImageNotFound);
                }
            });
            threads[threadCounter].start();
            threadCounter++;
        } else if (AppConstant.DROP_BOX_SELECTION == aNote.getStorageSelection()) {
            threads[threadCounter] = new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        Drawable drawable = getImageFromDropbox(mDropboxAPI,
                                AppSharedPreferences.getDropBoxUploadPath(getApplicationContext()),
                                aNote.getImagePath());
                        if (drawable != null) {
                            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                            aNote.setBitmap(bitmap);
                        }
                        if (!mIsImageNotFound) {
                            mNotesAdapter.setData(mNotes);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mNotesAdapter.notifyImageObtained();
                                }
                            });
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    } while (mIsImageNotFound);
                }
            });
            threads[threadCounter].start();
            threadCounter++;
        } else {
            aNote.setHasNoImage(true);
        }
    }
    mNotesAdapter.setData(mNotes); //Adapter has the latest copy of note
    changeNoItemTag();
}