Example usage for android.widget ImageView setImageBitmap

List of usage examples for android.widget ImageView setImageBitmap

Introduction

In this page you can find the example usage for android.widget ImageView setImageBitmap.

Prototype

@android.view.RemotableViewMethod
public void setImageBitmap(Bitmap bm) 

Source Link

Document

Sets a Bitmap as the content of this ImageView.

Usage

From source file:com.android.calendar.event.EventLocationAdapter.java

@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    View view = convertView;/*  w  ww . j  a v a 2  s . c  om*/
    if (view == null) {
        view = mInflater.inflate(R.layout.location_dropdown_item, parent, false);
    }
    final Result result = getItem(position);
    if (result == null) {
        return view;
    }

    // Update the display name in the item in auto-complete list.
    TextView nameView = (TextView) view.findViewById(R.id.location_name);
    if (nameView != null) {
        if (result.mName == null) {
            nameView.setVisibility(View.GONE);
        } else {
            nameView.setVisibility(View.VISIBLE);
            nameView.setText(result.mName);
        }
    }

    // Update the address line.
    TextView addressView = (TextView) view.findViewById(R.id.location_address);
    if (addressView != null) {
        addressView.setText(result.mAddress);
    }

    // Update the icon.
    final ImageView imageView = (ImageView) view.findViewById(R.id.icon);
    if (imageView != null) {
        if (result.mDefaultIcon == null) {
            imageView.setVisibility(View.INVISIBLE);
        } else {
            imageView.setVisibility(View.VISIBLE);
            imageView.setImageResource(result.mDefaultIcon);

            // Save the URI on the view, so we can check against it later when updating
            // the image.  Otherwise the async image update with using 'convertView' above
            // resulted in the wrong list items being updated.
            imageView.setTag(result.mContactPhotoUri);
            if (result.mContactPhotoUri != null) {
                Bitmap cachedPhoto = mPhotoCache.get(result.mContactPhotoUri);
                if (cachedPhoto != null) {
                    // Use photo in cache.
                    imageView.setImageBitmap(cachedPhoto);
                } else {
                    // Asynchronously load photo and update.
                    asyncLoadPhotoAndUpdateView(result.mContactPhotoUri, imageView);
                }
            }
        }
    }
    return view;
}

From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java

private void RotatePicture(ImageView imageView) {
    Bitmap picture = null;/*from ww  w.  j a  v  a2 s  . c om*/

    picture = ((BitmapDrawable) (imageView.getDrawable())).getBitmap();

    Matrix m = new Matrix();
    m.postRotate(90);
    picture = Bitmap.createBitmap(picture, 0, 0, picture.getWidth(), picture.getHeight(), m, true);

    imageView.setImageBitmap(picture);

}

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

/**
 * Same as download but the image is always downloaded and the cache is not
 * used. Kept private at the moment as its interest is not clear.
 *//*from  ww  w .j  av  a2  s . c o m*/
private void forceDownload(String url, final ImageView imageView) {
    // State sanity: url is guaranteed to never be null in
    // DownloadedDrawable and cache keys.
    if (url == null) {
        // imageView.setImageDrawable(null);
        handler.post(new Runnable() {
            @Override
            public void run() {
                imageView.setImageDrawable(null);
            }
        });
        return;
    }

    if (cancelPotentialDownload(url, imageView)) {
        switch (mode) {
        case NO_ASYNC_TASK:
            final Bitmap bitmap = downloadBitmap(url);
            addBitmapToCache(url, bitmap);
            // imageView.setImageBitmap(bitmap);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });
            break;

        case NO_DOWNLOADED_DRAWABLE:
            // imageView.setMinimumHeight(156);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setMinimumHeight(156);
                }
            });
            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
            task.execute(url);
            break;

        case CORRECT:
            task = new BitmapDownloaderTask(imageView);
            final DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
            // imageView.setImageDrawable(downloadedDrawable);
            // imageView.setMinimumHeight(156);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageDrawable(downloadedDrawable);
                    imageView.setMinimumHeight(156);
                }
            });
            task.execute(url);
            break;
        }
    }
}

From source file:com.example.sans.myapplication.Login.OnlineActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_online);

    shares = getSharedPreferences("SHARES", 0);

    Fragment newFragment = new OnlineBotFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.login_bot, newFragment);
    transaction.addToBackStack(null);//from  w w w  .  j  a  va2 s.c  om
    transaction.commit();

    transaction = getFragmentManager().beginTransaction();
    newFragment = new LoginTopFragment();
    transaction.replace(R.id.login_top, newFragment);
    transaction.commit();

    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu

    header = navigationView.inflateHeaderView(R.layout.header);
    JSONObject driver_data = null;
    try {
        driver_data = new JSONObject(shares.getString("DRIVER_DATA", "ERROR"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    TextView driver_name_header = (TextView) header.findViewById(R.id.username);
    TextView car_id_header = (TextView) header.findViewById(R.id.car_id);
    final ImageView pp_header = (ImageView) header.findViewById(R.id.profile_image);

    try {
        car_id_header.setText(driver_data.getString("license"));
        driver_name_header.setText(driver_data.getString("name"));
        Client client = new Client();
        client.get(driver_data.getString("image"),
                new FileAsyncHttpResponseHandler(OnlineActivity.this.getApplicationContext()) {
                    @Override
                    public void onFailure(int i, Header[] headers, Throwable throwable, File file) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final File response) {

                        OnlineActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap image = BitmapFactory.decodeFile(response.getPath());

                                pp_header.setImageBitmap(image);

                            }
                        });

                    }

                });
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        SharedPreferences.Editor editor = shares.edit();

        final Client client1 = new Client();
        RequestParams params1 = new RequestParams();

        editor.putBoolean("ONLINE", false);
        editor.putBoolean("LOGIN", false);
        editor.commit();
        Intent intent = getApplicationContext().getPackageManager()
                .getLaunchIntentForPackage(getApplicationContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

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

            Intent i = new Intent(OnlineActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", 0);
            OnlineActivity.this.startActivity(i);
            drawerLayout.closeDrawers();
        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state

            nav = true;

            menuItem.setChecked(false);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment fragment;
            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {
            case R.id.timetable:
            case R.id.service:
            case R.id.history:
            case R.id.mission:
            case R.id.points:
            case R.id.notice:
                Intent i = new Intent(OnlineActivity.this, MenuItemActivity.class);
                i.putExtra("MENU_ITEM", menuItem.getItemId());
                OnlineActivity.this.startActivity(i);
                break;
            case R.id.login:
                Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = shares.edit();

                final Client client = new Client();
                RequestParams params = new RequestParams();
                params.put("id", shares.getInt("ID", 0));
                params.put("status", 999);
                client.post("driver/setStatus", params, new JsonHttpResponseHandler());

                editor.putBoolean("ONLINE", false);
                editor.putBoolean("LOGIN", false);
                editor.commit();
                Intent intent = getApplicationContext().getPackageManager()
                        .getLaunchIntentForPackage(getApplicationContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                break;

            }
            return false;
        }
    });

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
            drawerLayout.setSelected(false);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    actionBarDrawerToggle.syncState();
}

From source file:com.google.android.apps.iosched.ui.SessionDetailFragment.java

private void onSpeakersQueryComplete(Cursor cursor) {
    try {/*from  w  ww .java 2 s.c o  m*/
        mSpeakersCursor = true;
        // TODO: remove any existing speakers from layout, since this cursor
        // might be from a data change notification.
        final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block);
        final LayoutInflater inflater = getActivity().getLayoutInflater();

        boolean hasSpeakers = false;

        while (cursor.moveToNext()) {
            final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME);
            if (TextUtils.isEmpty(speakerName)) {
                continue;
            }

            final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL);
            final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY);
            final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL);
            final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT);

            String speakerHeader = speakerName;
            if (!TextUtils.isEmpty(speakerCompany)) {
                speakerHeader += ", " + speakerCompany;
            }

            final View speakerView = inflater.inflate(R.layout.speaker_detail, speakersGroup, false);
            final TextView speakerHeaderView = (TextView) speakerView.findViewById(R.id.speaker_header);
            final ImageView speakerImgView = (ImageView) speakerView.findViewById(R.id.speaker_image);
            final TextView speakerUrlView = (TextView) speakerView.findViewById(R.id.speaker_url);
            final TextView speakerAbstractView = (TextView) speakerView.findViewById(R.id.speaker_abstract);

            if (!TextUtils.isEmpty(speakerImageUrl)) {
                BitmapUtils.fetchImage(getActivity(), speakerImageUrl, null, null,
                        new BitmapUtils.OnFetchCompleteListener() {
                            public void onFetchComplete(Object cookie, Bitmap result) {
                                if (result != null) {
                                    speakerImgView.setImageBitmap(result);
                                }
                            }
                        });
            }

            speakerHeaderView.setText(speakerHeader);
            UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract);

            if (!TextUtils.isEmpty(speakerUrl)) {
                UIUtils.setTextMaybeHtml(speakerUrlView, speakerUrl);
                speakerUrlView.setVisibility(View.VISIBLE);
            } else {
                speakerUrlView.setVisibility(View.GONE);
            }

            speakersGroup.addView(speakerView);
            hasSpeakers = true;
            mHasSummaryContent = true;
        }

        speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE);

        // Show empty message when all data is loaded, and nothing to show
        if (mSessionCursor && !mHasSummaryContent) {
            mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
        }
    } finally {
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:com.android.calendar.event.EventLocationAdapter.java

private void asyncLoadPhotoAndUpdateView(final Uri contactPhotoUri, final ImageView imageView) {
    AsyncTask<Void, Void, Bitmap> photoUpdaterTask = new AsyncTask<Void, Void, Bitmap>() {
        @Override/*from w w  w  .  ja va  2  s.  co m*/
        protected Bitmap doInBackground(Void... params) {
            Bitmap photo = null;
            InputStream imageStream = Contacts.openContactPhotoInputStream(mResolver, contactPhotoUri);
            if (imageStream != null) {
                photo = BitmapFactory.decodeStream(imageStream);
                mPhotoCache.put(contactPhotoUri, photo);
            }
            return photo;
        }

        @Override
        public void onPostExecute(Bitmap photo) {
            // The View may have already been reused (because using 'convertView' above), so
            // we must check the URI is as expected before setting the icon, or we may be
            // setting the icon in other items.
            if (photo != null && imageView.getTag() == contactPhotoUri) {
                imageView.setImageBitmap(photo);
            }
        }
    }.execute();
}

From source file:edu.sfsu.cs.orange.ocr.CaptureActivity.java

/**
 * Displays information relating to the result of OCR, and requests a translation if necessary.
 * //  w  w  w  . j a  v  a 2 s .co  m
 * @param ocrResult Object representing successful OCR results
 * @return True if a non-null result was received for OCR
 */
boolean handleOcrDecode(OcrResult ocrResult) {
    lastResult = ocrResult;

    // Test whether the result is null
    if (ocrResult.getText() == null || ocrResult.getText().equals("")) {
        Toast toast = Toast.makeText(this, "OCR failed. Please try again.", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        return false;
    }

    // Turn off capture-related UI elements
    shutterButton.setVisibility(View.GONE);
    statusViewBottom.setVisibility(View.GONE);
    statusViewTop.setVisibility(View.GONE);
    cameraButtonView.setVisibility(View.GONE);
    viewfinderView.setVisibility(View.GONE);
    resultView.setVisibility(View.VISIBLE);

    ImageView bitmapImageView = (ImageView) findViewById(R.id.image_view);
    lastBitmap = ocrResult.getBitmap();
    if (lastBitmap == null) {
        bitmapImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    } else {
        bitmapImageView.setImageBitmap(lastBitmap);
    }

    // Display the recognized text
    TextView sourceLanguageTextView = (TextView) findViewById(R.id.source_language_text_view);
    sourceLanguageTextView.setText(sourceLanguageReadable);
    TextView ocrResultTextView = (TextView) findViewById(R.id.ocr_result_text_view);
    ocrResultTextView.setText(ocrResult.getText());

    String rawText = ocrResult.getText();
    rawText.split("\n");
    String[] beerNames = rawText.split("\n");

    for (String beer : beerNames) {
        beerQuery.asyncBeerFetch(beer, aq);
    }

    ocrResultTextView.setText(aq.getText());

    // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
    int scaledSize = Math.max(22, 32 - ocrResult.getText().length() / 4);
    ocrResultTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

    TextView translationLanguageLabelTextView = (TextView) findViewById(
            R.id.translation_language_label_text_view);
    TextView translationLanguageTextView = (TextView) findViewById(R.id.translation_language_text_view);
    TextView translationTextView = (TextView) findViewById(R.id.translation_text_view);

    translationLanguageLabelTextView.setVisibility(View.GONE);
    translationLanguageTextView.setVisibility(View.GONE);
    translationTextView.setVisibility(View.GONE);
    progressView.setVisibility(View.GONE);
    setProgressBarVisibility(false);

    return true;
}

From source file:com.DGSD.Teexter.Utils.ContactPhotoManager.java

/**
 * Checks if the photo is present in cache. If so, sets the photo on the
 * view.// ww w  . j a  va  2  s  . c om
 * 
 * @return false if the photo needs to be (re)loaded from the provider.
 */
private boolean loadCachedPhoto(ImageView view, Request request) {
    BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
    if (holder == null) {
        // The bitmap has not been loaded - should display the placeholder
        // image.
        request.applyDefaultImage(view);
        return false;
    }

    if (holder.bytes == null) {
        request.applyDefaultImage(view);
        return holder.fresh;
    }

    // Optionally decode bytes into a bitmap
    inflateBitmap(holder);

    view.setImageBitmap(holder.bitmap);

    if (holder.bitmap != null) {
        // Put the bitmap in the LRU cache
        mBitmapCache.put(request, holder.bitmap);
    }

    // Soften the reference
    holder.bitmap = null;

    return holder.fresh;
}

From source file:com.google.android.imageloader.ImageLoader.java

/**
 * Binds an image at the given URL to an {@link ImageView}.
 * <p>/*from  www.  j a va 2 s  .  c  o m*/
 * If the image needs to be loaded asynchronously, it will be assigned at a
 * later time, replacing any existing {@link Drawable} unless
 * {@link #unbind(ImageView)} is called or
 * {@link #bind(ImageView, String, Callback)} is called with the same
 * {@link ImageView}, but a different URL.
 * <p>
 * Use {@link #bind(BaseAdapter, ImageView, String)} instead of this method
 * when the {@link ImageView} is in an {@link android.widget.AdapterView} so
 * that the image will be bound correctly in the case where it has been
 * assigned to a different position since the asynchronous request was
 * started.
 *
 * @param view the {@link ImageView} to bind.
 * @param url the image URL.s
 * @param callback invoked after the image has finished loading or after an
 *            error. The callback may be executed before this method returns
 *            when the result is cached. This parameter can be {@code null}
 *            if a callback is not required.
 * @return a {@link BindResult}.
 * @throws NullPointerException if a required argument is {@code null}
 */
public BindResult bind(ImageView view, String url, Callback callback) {
    if (view == null) {
        throw new NullPointerException("ImageView is null");
    }
    if (url == null) {
        throw new NullPointerException("URL is null");
    }
    mImageViewBinding.put(view, url);
    Bitmap bitmap = getBitmap(url);
    ImageError error = getError(url);
    if (bitmap != null) {
        view.setImageBitmap(bitmap);
        if (callback != null) {
            callback.onImageLoaded(view, url);
        }
        return BindResult.OK;
    } else {
        // Clear the ImageView by default.
        // The caller can set their own placeholder
        // based on the return value.
        view.setImageDrawable(null);

        if (error != null) {
            if (callback != null) {
                callback.onImageError(view, url, error.getCause());
            }
            return BindResult.ERROR;
        } else {
            ImageRequest request = new ImageRequest(view, url, callback);
            enqueueRequest(request);
            return BindResult.LOADING;
        }
    }
}

From source file:com.nd.pad.GreenBrowser.util.ImageDownloader.java

/**
* Download the specified image from the Internet and binds it to the
* provided ImageView. The binding is immediate if the image is found in the
* cache and will be done asynchronously otherwise. A null bitmap will be
* associated to the ImageView if an error occurs.
* 
* @param url// w ww  . j a  va  2 s .  c o  m
*            The URL of the image to download.
* @param imageView
*            The ImageView to bind the downloaded image to.
*/
public void download(String url, ImageView imageView, int loadingDrawable_ID, int failDrawable_ID,
        boolean isSaveLocal) {
    Bitmap bitmap = getBitmapFromCache(url);
    /*  */
    if (bitmap == null && isSaveLocal) {
        bitmap = getBitmapFromLocal(url, Constants.FILE_CACHE);
    }
    /*  */
    if (bitmap == null) {
        forceDownload(url, imageView, loadingDrawable_ID, failDrawable_ID, isSaveLocal, null);
    } else {
        cancelPotentialDownload(url, imageView);
        imageView.setImageBitmap(bitmap);
    }
}