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.fn.reunion.app.ui.base.AppBaseActivity.java

public ArrayList<HashMap<String, String>> getUserList() throws Exception {

    ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>();
    if (connection != null) {
        Roster roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();
        for (RosterEntry entry : entries) {
            String avatarPath = "";
            ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider());
            VCard vCard = new VCard();
            try {
                vCard.load(connection, entry.getUser());
                vCard.getExtensions();//  ww w .j  a v  a 2 s . c  o m
                byte[] b = vCard.getAvatar();
                Bitmap avatar = BitmapFactory.decodeByteArray(vCard.getAvatar(), 0, b.length);
                //  avatarPath = savaAvatar(avatar, entry.getUser());
            } catch (Exception e) {
            }

            HashMap<String, String> user = new HashMap<String, String>();
            user.put("name", entry.getName());
            user.put("userid", entry.getUser());
            user.put("statusMsg", "" + entry.getStatus());
            user.put("user_avatar", avatarPath);
            user.put("status", "" + connection.getRoster().getPresence(entry.getUser()).isAvailable());
            userList.add(user);
        }
    }
    return userList;
}

From source file:com.nttec.everychan.cache.BitmapCache.java

/**
 *   ?  ?   /*from   w w  w.ja  v a 2 s  . c o m*/
 * @param hash ? ( ? )
 * @param url ? URL (?  ? )
 * @param maxSize ?   ??,     ,  0, ? ?? ?  ?
 * @param chan   ? 
 * @param task ?? 
 * @return Bitmap ? ,  null, ?   ?
 */
public Bitmap download(String hash, String url, int maxSize, ChanModule chan, CancellableTask task) {
    if (hash == null) {
        Logger.e(TAG, "received null hash; url: " + url);
        return null;
    }

    synchronized (currentDownloads) {
        while (currentDownloads.contains(hash)) {
            try {
                currentDownloads.wait();
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }
        currentDownloads.add(hash);
    }

    try {
        Bitmap bmp = getFromCache(hash);
        if (bmp != null)
            return bmp;
        try {
            class BufOutputStream extends ByteArrayOutputStream {
                public BufOutputStream() {
                    super(1024);
                }

                public InputStream toInputStream() {
                    return new ByteArrayInputStream(buf, 0, count);
                }
            }
            BufOutputStream data = new BufOutputStream();
            chan.downloadFile(url, data, null, task);
            bmp = BitmapFactory.decodeStream(data.toInputStream());
        } catch (Exception e) {
            Logger.e(TAG, e);
            if (url.startsWith("data:image")) {
                try {
                    byte[] data = Base64.decode(url.substring(url.indexOf("base64,") + 7), Base64.DEFAULT);
                    bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                } catch (Exception e1) {
                    Logger.e(TAG, e1);
                }
            }
        }
        if (bmp == null || (task != null && task.isCancelled())) {
            return null;
        }

        if (maxSize > 0) { // 
            double scale = (double) maxSize / Math.max(bmp.getWidth(), bmp.getHeight());
            if (scale < 1.0) {
                int width = (int) (bmp.getWidth() * scale);
                int height = (int) (bmp.getHeight() * scale);
                if (Math.min(width, height) > 0) {
                    Bitmap scaled = Bitmap.createScaledBitmap(bmp, width, height, true);
                    bmp.recycle();
                    bmp = scaled;
                }
            }
        }

        OutputStream fileStream = null;
        File file = null;
        boolean success = true;
        try {
            lru.put(hash, bmp);
            file = fileCache.create(FileCache.PREFIX_BITMAPS + hash);
            fileStream = new FileOutputStream(file);
            if (!bmp.compress(Bitmap.CompressFormat.PNG, 100, fileStream)) {
                throw new Exception();
            }
            fileStream.close();
            fileCache.put(file);
            fileStream = null;
        } catch (Exception e) {
            success = false;
            Logger.e(TAG, e);
        } finally {
            IOUtils.closeQuietly(fileStream);
            if (!success && file != null)
                fileCache.abort(file);
        }
        return bmp;

    } catch (OutOfMemoryError oom) {
        MainApplication.freeMemory();
        Logger.e(TAG, oom);
        return null;

    } finally {
        synchronized (currentDownloads) {
            currentDownloads.remove(hash);
            currentDownloads.notifyAll();
        }
    }
}

From source file:net.networksaremadeofstring.rhybudd.ZenossWidgetGraph.java

private Bitmap RenderBarGraph(int CritCount, int ErrCount, int WarnCount) {

    //Log.i("Counts", Integer.toString(CritCount) + " / " + Integer.toString(ErrCount) + " / " + Integer.toString(WarnCount));
    Bitmap emptyBmap = Bitmap.createBitmap(290, 150, Config.ARGB_8888);

    int width = emptyBmap.getWidth();
    int height = emptyBmap.getHeight();
    Bitmap charty = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(charty);
    //final int color = 0xff0B0B61; 
    final Paint paint = new Paint();

    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.WHITE);/*w w  w  .  j a va2  s  .  c  o m*/

    //y
    canvas.drawLine(25, 0, 25, 289, paint);
    //x
    canvas.drawLine(25, 149, 289, 149, paint);

    paint.setAntiAlias(true);
    int Max = 0;

    if (CritCount > ErrCount && CritCount > WarnCount)
        Max = CritCount;
    else if (ErrCount > CritCount && ErrCount > WarnCount)
        Max = ErrCount;
    else if (WarnCount > CritCount && WarnCount > ErrCount)
        Max = WarnCount;
    else
        Max = CritCount;

    if (Max > 0)
        canvas.drawText(Integer.toString(Max), 0, 10, paint);

    if (Max > 1)
        canvas.drawText(Integer.toString(Max / 2), 0, 75, paint);

    canvas.drawText("0", 0, 148, paint);

    double divisor = 148 / (double) Max;

    paint.setAlpha(128);

    Rect rect = new Rect(32, (int) (148 - (divisor * CritCount)), 64, 148);
    paint.setColor(Color.argb(200, 208, 0, 0)); //red

    if (CritCount > 0)
        canvas.drawRect(new RectF(rect), paint);

    rect = new Rect(128, (int) (148 - (divisor * ErrCount)), 160, 148);
    paint.setColor(Color.argb(200, 255, 102, 0));//orange

    if (ErrCount > 0)
        canvas.drawRect(new RectF(rect), paint);

    rect = new Rect(224, (int) (148 - (divisor * WarnCount)), 256, 148);
    paint.setColor(Color.argb(200, 255, 224, 57)); //yellow
    if (WarnCount > 0)
        canvas.drawRect(new RectF(rect), paint);

    //Return
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    charty.compress(CompressFormat.PNG, 50, out);

    return BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
}

From source file:com.ubikod.capptain.android.sdk.reach.CapptainReachInteractiveContent.java

/**
 * Get notification image for in app notifications. For system notification this field corresponds
 * to the large icon (displayed only on Android 3+).
 * @return notification image.//from  w ww  . ja v  a  2 s  .  c  o m
 */
public Bitmap getNotificationImage() {
    /* Decode as bitmap now if not already done */
    if (mNotificationImageString != null && mNotificationImage == null) {
        /* Decode base 64 then decode as a bitmap */
        byte[] data = Base64.decode(mNotificationImageString);
        if (data != null)
            try {
                mNotificationImage = BitmapFactory.decodeByteArray(data, 0, data.length);
            } catch (OutOfMemoryError e) {
                /* Abort */
            }

        /* On any error, don't retry next time */
        if (mNotificationImage == null)
            mNotificationImageString = null;
    }
    return mNotificationImage;
}

From source file:com.HumanDecisionSupportSystemsLaboratory.DD_P2P.Safe.java

public static void loadPeer() {
    Log.d("onCreateView", "Safe: loadPeer: start");
    /*/*from  w w w.  j  av a  2 s . co  m*/
     * very IMPORTANT! The list and peers must be clear every time when the
     * Fragment get created, otherwise, duplicate entries might occur!!!
     */
    list.clear();
    peers.clear();

    synchronized (Orgs.monitor) {
        // pull out all safes from database
        if (Application_GUI.dbmail == null)
            Application_GUI.dbmail = new Android_DB_Email(Safe.safeItself.getActivity());
        if (Application_GUI.gui == null)
            Application_GUI.gui = new Android_GUI();
        if (Application.db == null) {
            try {

                DBInterface db = new DBInterface("deliberation-app.db");
                Application.db = db;
            } catch (P2PDDSQLException e1) {
                e1.printStackTrace();
            }
        }
    }
    Log.d("onCreateView", "Safe: loadPeer: database loaded");

    ArrayList<ArrayList<Object>> peer_IDs = D_Peer.getAllPeers();
    Log.d("onCreateView", "Safe: loadPeer: found peers: #" + peer_IDs.size());

    if (peer_IDs.size() == 0) {
        // testPeerCreation();
        // peer_IDs = D_Peer.getAllPeers();
        // Log.d("onCreateView", "Safe: onCreateView: re-found peers: #" +
        // peer_IDs.size());
    } else {
        Main.startServers();
    }

    for (ArrayList<Object> peer_data : peer_IDs) {
        if (peer_data.size() <= 0)
            continue;
        String p_lid = Util.getString(peer_data.get(0));
        D_Peer peer = D_Peer.getPeerByLID(p_lid, true, false);
        if (peer == null || (SAFE_HIDE && peer.getHidden()))
            continue;
        peers.add(peer);
    }

    Log.d("onCreateView", "Safe: loadPeer: build peers data for #" + peers.size());
    data = new String[peers.size()][];
    Log.d(TAG, "safe data size: " + data.length);

    imgData = new ArrayList<Bitmap>();

    for (int k = 0; k < peers.size(); k++) {
        D_Peer p = peers.get(k);

        // if a safe has private key then use getname... to be implemented
        data[k] = new String[] { p.getName_MyOrDefault(), p.getEmail(), p.getSlogan_MyOrDefault() };

        boolean gotIcon = false;
        try {
            byte[] icon = p.getIcon();
            if (icon != null) {
                Bitmap bmp = BitmapFactory.decodeByteArray(icon, 0, icon.length - 1);
                gotIcon = true;
                Log.d(TAG, "image bmp: " + bmp.toString());
                imgData.add(bmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!gotIcon) {
            int imgId = R.drawable.placeholder;
            Log.d(TAG, "image path: " + imgId);
            Bitmap bmp = PhotoUtil.decodeSampledBitmapFromResource(Safe.safeItself.getResources(), imgId, 55,
                    55);
            Log.d(TAG, "image bmp: " + bmp.toString());
            imgData.add(bmp);
        }
    }
    if (data.length > 0 && data[0].length > 0)
        Log.d(TAG, "safe name: " + data[0][0]);
    /*
     * Identity.init_Identity();
     * 
     * HandlingMyself_Peer.loadIdentity(null);
     * 
     * try { DD.startUServer(true, Identity.current_peer_ID);
     * DD.startServer(false, Identity.current_peer_ID);
     * DD.startClient(true);
     * 
     * } catch (NumberFormatException | P2PDDSQLException e) {
     * System.err.println("Safe: onCreateView: error"); e.printStackTrace();
     * }
     * 
     * try { DD.load_listing_directories(); } catch (NumberFormatException |
     * UnknownHostException | P2PDDSQLException e) { e.printStackTrace(); }
     * D_Peer myself = HandlingMyself_Peer.get_myself();
     * myself.addAddress(Identity.listing_directories_addr.get(0), true,
     * null);
     */

    // end of data pulling out

    Log.d("onCreateView", "Safe: onCreateView: fill GUI list");
    // using a map datastructure to store data for listview
    /*
     * for (int i = 0; i < this.data.length; i++) { Map<String, String> map
     * = new HashMap<String, String>(); map.put("name", this.data[i][0]);
     * map.put("email", this.data[i][1]); map.put("slogan",
     * this.data[i][2]);
     * 
     * map.put("pic", String.valueOf(R.drawable.placeholder));
     * 
     * this.list.add(map); }
     */

    for (int i = 0; i < Safe.data.length; i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put(SAFE_LIST_NAME, Safe.data[i][0]);
        map.put(SAFE_LIST_EMAIL, Safe.data[i][1]);
        map.put(SAFE_LIST_SLOGAN, Safe.data[i][2]);

        map.put("pic", String.valueOf(R.drawable.placeholder));

        list.add(map);
    }

    Log.d(TAG, "safe size: " + list.size());

    Log.d(TAG, "safe: list hash at safe: " + list.hashCode() + " size: " + Safe.list.size());
}

From source file:com.fastbootmobile.encore.app.fragments.RecognitionFragment.java

private void loadAlbumArt(final String urlString, final ImageView iv) {
    new Thread() {
        public void run() {
            URL url;/*  w w w  . ja v a 2  s. co m*/
            try {
                url = new URL(urlString);
            } catch (MalformedURLException e) {
                // Too bad
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mIvArt.setImageResource(R.drawable.album_placeholder);
                    }
                });
                return;
            }

            Log.d(TAG, "Loading album art: " + urlString);

            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStream is = conn.getInputStream();
                byte[] buffer = new byte[8192];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int read;
                while ((read = is.read(buffer)) > 0) {
                    baos.write(buffer, 0, read);
                }

                final Bitmap bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
                if (bmp != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            iv.setImageBitmap(bmp);
                            iv.setVisibility(View.VISIBLE);
                        }
                    });
                } else {
                    Log.e(TAG, "Null bitmap from image");
                }
            } catch (IOException e) {
                Log.e(TAG, "Error downloading album art", e);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        iv.setImageResource(R.drawable.album_placeholder);
                        iv.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }.start();
}

From source file:com.rnd.snapsplit.view.OwedFragment.java

@Nullable
@Override/*from   w w w.  j  a va 2s .  c  o  m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.activity_owed, container, false);
    activity = getActivity();
    profile = new Profile(getContext());
    ((Toolbar) getActivity().findViewById(R.id.tool_bar_hamburger)).setVisibility(View.VISIBLE);

    mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(getContext());
    //mLinearLayoutManager.setStackFromEnd(true);
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("requests");
    mFirebaseAdapter = new FirebaseRecyclerAdapter<PaymentRequest, MessageViewHolder>(PaymentRequest.class,
            R.layout.list_owed, MessageViewHolder.class,
            mFirebaseDatabaseReference.orderByChild("requestEpochDate")) {

        @Override
        protected PaymentRequest parseSnapshot(DataSnapshot snapshot) {
            PaymentRequest pr = super.parseSnapshot(snapshot);
            if (pr != null) {
                pr.setId(snapshot.getKey());
                return pr;
            }
            return null;
        }

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, PaymentRequest pr, int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (pr != null && pr.getReceipientPhoneNo().equals(profile.getPhoneNumber())) {

                if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                    String encodedReceipt = pr.getStrReceiptPic();
                    byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    viewHolder.receiptIcon.setImageBitmap(bitmap);
                }
                viewHolder.pr = pr;
                viewHolder.id = pr.getId();
                viewHolder.description.setText(pr.getDescription());
                viewHolder.from.setText(
                        "Request sent by: " + pr.getRequestorName() + " - " + pr.getRequestorPhoneNumber());
                viewHolder.share.setText("Your Share: HKD" + String.format("%.2f", pr.getShareAmount()));
                viewHolder.splitAmount
                        .setText("Total Amount: HKD" + String.format("%.2f", pr.getTotalAmount()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
                String date = null;
                Date temp = new Date(Long.parseLong(pr.getRequestEpochDate()) * (-1));
                date = simpleDateFormat.format(temp);
                viewHolder.date.setText(date);
            } else {
                ViewGroup.LayoutParams params = viewHolder.item.getLayoutParams();
                params.height = 0;
                viewHolder.item.setLayoutParams(params);
            }

            // log a view action on it
            //FirebaseUserActions.getInstance().end(getMessageViewAction(fd));
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MessageViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.setOnLongClickListener(new MessageViewHolder.LongClickListener() {
                @Override
                public void onLongClick(View view, int position, String id, PaymentRequest pr) {
                    AlertDialog.Builder ImageDialog = new AlertDialog.Builder(getActivity());
                    ImageDialog.setTitle("Receipt Preview - " + pr.getDescription());
                    ImageView showImage = new ImageView(getActivity());
                    Bitmap bitmap = null;
                    if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                        String encodedReceipt = pr.getStrReceiptPic();
                        byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                        bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    }
                    if (bitmap != null) {
                        showImage.setImageBitmap(bitmap);
                    }
                    ImageDialog.setView(showImage);

                    ImageDialog.setNegativeButton("Close Preview", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    ImageDialog.show();
                }
            });
            viewHolder.setOnClickListener(new MessageViewHolder.ClickListener() {
                @Override
                public void onItemClick(View view, int position, String id, PaymentRequest pr) {
                    //Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("pr", pr);

                    if (initCipher(mCipher, DEFAULT_KEY_NAME)) {
                        // Show the fingerprint dialog. The user has the option to use the fingerprint with
                        // crypto, or you can fall back to using a server-side verified password.
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        boolean useFingerprintPreference = mSharedPreferences
                                .getBoolean(getString(R.string.use_fingerprint_to_authenticate_key), true);
                        if (useFingerprintPreference) {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.FINGERPRINT);
                        } else {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.PASSWORD);
                        }
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    } else {
                        // This happens if the lock screen has been disabled or or a fingerprint got
                        // enrolled. Thus show the dialog to authenticate with their password first
                        // and ask the user if they want to authenticate with fingerprints in the
                        // future
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        fragment.setStage(
                                DialogFragmentFingerprintAuthentication.Stage.NEW_FINGERPRINT_ENROLLED);
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    }
                }

            });
            return viewHolder;
        }

    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }
    try {
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    }
    //Cipher defaultCipher;
    Cipher cipherNotInvalidated;
    try {
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        cipherNotInvalidated = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    KeyguardManager keyguardManager = getActivity().getSystemService(KeyguardManager.class);
    FingerprintManager fingerprintManager = getActivity().getSystemService(FingerprintManager.class);

    if (!keyguardManager.isKeyguardSecure()) {
        // Show a message that the user hasn't set up a fingerprint or lock screen.
        Toast.makeText(getActivity(),
                "Secure lock screen hasn't set up.\n"
                        + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    // Now the protection level of USE_FINGERPRINT permission is normal instead of dangerous.
    // See http://developer.android.com/reference/android/Manifest.permission.html#USE_FINGERPRINT
    // The line below prevents the false positive inspection from Android Studio
    // noinspection ResourceType
    if (!fingerprintManager.hasEnrolledFingerprints()) {
        // This happens when no fingerprints are registered.
        Toast.makeText(getActivity(),
                "Go to 'Settings -> Security -> Fingerprint' and register at least one fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    createKey(DEFAULT_KEY_NAME, true);
    createKey(KEY_NAME_NOT_INVALIDATED, false);

    return view;

}

From source file:no.ntnu.idi.socialhitchhiking.Main.java

/**
 * Gets the Facebook profile pucture of the given {@link User}.
 * @param user/*ww w. j  av a2 s  . c  o m*/
 * @return
 */
private Bitmap getFacebookPicture(User user) {
    Bitmap bm = BitmapFactory.decodeByteArray(user.getPicture(), 0, user.getPicture().length);
    return bm;
}

From source file:com.example.gtuandroid.component.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    Bitmap webImg = null;//  w w  w  .  j  av  a  2s.c  o m
    try {
        URL imgUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) imgUrl.openConnection();
        httpURLConnection.connect();
        InputStream inputStream = httpURLConnection.getInputStream();
        int length = httpURLConnection.getContentLength();
        int tmpLength = 512;
        int readLen = 0, desPos = 0;
        byte[] img = new byte[length];
        byte[] tmp = new byte[tmpLength];
        if (length != -1) {
            while ((readLen = inputStream.read(tmp)) > 0) {
                System.arraycopy(tmp, 0, img, desPos, readLen);
                desPos += readLen;
            }
            webImg = BitmapFactory.decodeByteArray(img, 0, img.length);
            if (desPos != length) {
                throw new IOException("Only read" + desPos + "bytes");
            }
        }
        httpURLConnection.disconnect();
    } catch (IOException e) {
        Log.e("IOException", e.toString());
    }
    return webImg;
}

From source file:ca.ualberta.app.activity.CreateAnswerActivity.java

@Override
public void onStart() {
    super.onStart();
    Intent intent = getIntent();/*from w  ww .java 2 s .c om*/
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if (extras.getBoolean(EDIT_MODE)) {
                String answerContent = extras.getString(ANSWER_CONTENT);
                contentText.setText(answerContent);
                try {
                    byte[] imageByteArray = Base64.decode(extras.getByteArray(IMAGE), Base64.NO_WRAP);
                    image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
                    scaleImage(THUMBIMAGESIZE, THUMBIMAGESIZE, true);
                    imageView.setVisibility(View.VISIBLE);
                    imageView.setImageBitmap(imageThumb);
                } catch (Exception e) {
                }

            }
        }
    }
}