logo
down
shadow

Android - Displaying the image in ImageView


Android - Displaying the image in ImageView

By : user2954015
Date : November 21 2020, 07:31 AM
like below fixes the issue when you "start an activity for result", your current activity is paused, and the new one (referenced by the intent) is started. Once it finishes whatever task it must perform, your previous activity is resumed, and the "onActivityResult" method is called.
On that method is where you have to load the picture and set it to your image view: (set photoFile as a instance variable of your activity)
code :
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        photoFile = null;
        try {
            photoFile = createImageFile(1);
        } catch (IOException e) {
            // Error occurred when creating a file
            System.out.println(e.getLocalizedMessage());
        }
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    switch(requestCode)
    {
    case REQUEST_IMAGE_CAPTURE:
        if(resultCode == RESULT_OK)
        {
            ImageView img = (ImageView) findViewById(R.id.image_front);
            img.setImageURI(Uri.fromFile(photoFile));
        }
        break;
    }
}


Share : facebook icon twitter icon
Android: Displaying .jpg image from sdcard using ImageView

Android: Displaying .jpg image from sdcard using ImageView


By : esraa aldeeb
Date : March 29 2020, 07:55 AM
wish help you to fix your issue do NOT access the SD card directly, try accessing it trough Environment. Like this:
code :
String imageDir = Environment.getExternalStorageDirectory()+"/apple.jpg";
Bitmap myBitmap = BitmapFactory.decodeFile(imageDir);
Android - Loading Image Url and Displaying in ImageView

Android - Loading Image Url and Displaying in ImageView


By : IfStatements
Date : March 29 2020, 07:55 AM
Hope this helps try with this class, it download the image in background and store in cache:
code :
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;




/**
 * This Class is for download images and assign the drawable to an ImageView.
 * 
 */
public class DrawableBackgroundDownloader {    

private final Map<String, Drawable> mCache = new HashMap<String, Drawable>();   
private final LinkedList <Drawable> mChacheController = new LinkedList <Drawable> ();
private ExecutorService mThreadPool;  
private final Map<ImageView, String> mImageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());  
public static int MAX_CACHE_SIZE = 80; 
public int THREAD_POOL_SIZE = 3;



/**
 * Constructor
 */
public DrawableBackgroundDownloader() {  
    mThreadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);  
}  


/**
 * Clears all instance data and stops running threads
*/ 
public void Reset() {
    ExecutorService oldThreadPool = mThreadPool;
    mThreadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    oldThreadPool.shutdownNow();

    mChacheController.clear();
    mCache.clear();
    mImageViews.clear();
}  

/**
 * Load the drawable associated to a url and assign it to an image, you can set a placeholder to replace this drawable.
 * @param url Is the url of the image.
 * @param imageView The image to assign the drawable.
 * @param placeholder A drawable that is show during the image is downloading.
 */
public void loadDrawable(final String url, final ImageView imageView,Drawable placeholder) {  
    if(!mImageViews.containsKey(url))
        mImageViews.put(imageView, url);  
    Drawable drawable = getDrawableFromCache(url);  

    // check in UI thread, so no concurrency issues  
    if (drawable != null) {  
        //Log.d(null, "Item loaded from mCache: " + url);  
        imageView.setImageDrawable(drawable);  
    } else {  
        imageView.setImageDrawable(placeholder);  
        queueJob(url, imageView, placeholder);  
    }  
} 


/**
 * Return a drawable from the cache.
 * @param url url of the image.
 * @return a Drawable in case that the image exist in the cache, else returns null.
 */
public Drawable getDrawableFromCache(String url) {  
    if (mCache.containsKey(url)) {  
        return mCache.get(url);  
    }  

    return null;  
}


/**
 * Save the image to cache memory.
 * @param url The image url
 * @param drawable The drawable to save.
 */
private synchronized void putDrawableInCache(String url,Drawable drawable) {  
    int chacheControllerSize = mChacheController.size();
    if (chacheControllerSize > MAX_CACHE_SIZE) 
        mChacheController.subList(0, MAX_CACHE_SIZE/2).clear();

    mChacheController.addLast(drawable);
    mCache.put(url, drawable);

}  

/**
 * Queue the job to download the image.
 * @param url Image url.
 * @param imageView The ImageView where is assigned the drawable.
 * @param placeholder The drawable that is show during the image is downloading. 
 */
private void queueJob(final String url, final ImageView imageView,final Drawable placeholder) {  
    /* Create handler in UI thread.  */
    final Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            String tag = mImageViews.get(imageView);  
            if (tag != null && tag.equals(url)) {
                if (imageView.isShown())
                    if (msg.obj != null) {
                        imageView.setImageDrawable((Drawable) msg.obj);  
                    } else {  
                        imageView.setImageDrawable(placeholder);  
                        //Log.d(null, "fail " + url);  
                    } 
            }  
        }  
    };  

    mThreadPool.submit(new Runnable() {  
        public void run() {  
            final Drawable bmp = downloadDrawable(url);
            // if the view is not visible anymore, the image will be ready for next time in cache
            if (imageView.isShown())
            {
                Message message = Message.obtain();  
                message.obj = bmp;
                //Log.d(null, "Item downloaded: " + url);  

                handler.sendMessage(message);
            }
        }  
    });  
}  


/**
 * Method that download the image
 * @param url The url image.
 * @return Returns the drawable associated to this image.
 */
private Drawable downloadDrawable(String url) {  
    try {  
        InputStream is = getInputStream(url);

        Drawable drawable = Drawable.createFromStream(is, url);
        putDrawableInCache(url,drawable);  
        return drawable;  

    } catch (MalformedURLException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  

    return null;  
}  

/**
 * This method manage the connection to download the image.
 * @param urlString url of the image.
 * @return Returns an InputStream associated with the url image.
 * @throws MalformedURLException
 * @throws IOException
 */
private InputStream getInputStream(String urlString) throws MalformedURLException, IOException {
    URL url = new URL(urlString);
    URLConnection connection;
    connection = url.openConnection();
    connection.setUseCaches(true); 
    connection.connect();
    InputStream response = connection.getInputStream();

    return response;
}
}
 DrawableBackgroundDownloader drawableDownloader = new DrawableBackgroundDownloader();
drawableDownloader.loadDrawable(String urlImage, ImageView iView,Drawable drawable);
Android: Crop image and Displaying it on ImageView

Android: Crop image and Displaying it on ImageView


By : Pu Cyong Gao
Date : March 29 2020, 07:55 AM
Hope that helps Ops i just neglected the null check everything is fine new updated code , error free code.
code :
     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        switch (requestCode) {
            case PICK_FROM_CAMERA:
                /**
                 * After taking a picture, do the crop
                 */
                doCrop();

                break;

            case PICK_FROM_FILE:
                /**
                 * After selecting image from files, save the selected path
                 */
                Toast.makeText(this,"in gall",Toast.LENGTH_LONG).show();
                mImageCaptureUri = data.getData();
               Log.e("URI", mImageCaptureUri.toString());
                doCrop();

                break;

            case crop:
                Log.e("URI2", mImageCaptureUri.toString());

                Bundle extras = data.getExtras();
                /**
                 * After cropping the image, get the bitmap of the cropped image and
                 * display it on imageview.
                 */
                    if(extras!=null)
{
                    Bitmap photo = extras.getParcelable("data");
                    Log.e("URI9", mImageCaptureUri.toString());
                    mImageView.setImageBitmap(photo);
}

                //    File f = new File(mImageCaptureUri.getPath());
                /**
                 * Delete the temporary image
                 */
                //  if (f.exists())
                //    f.delete();

                break;

        }
    }
Android: displaying image to ImageView using String as name of the image(in real device)

Android: displaying image to ImageView using String as name of the image(in real device)


By : ChengHsuanKao
Date : March 29 2020, 07:55 AM
will be helpful for those in need You don't need "@drawable/". That is what the second parameter to getIdentifier already does.
code :
getResources().getIdentifier(imgname, "drawable", getPackageName());
Android ImageView Is Not Displaying Image?

Android ImageView Is Not Displaying Image?


By : Chris Price
Date : March 29 2020, 07:55 AM
Hope that helps In my case, all my fragment's imageViews are not showing when I run my application. The problem is, I extend my "Activity" class from "FragmentActivity". so I just change it "FragmentActivity" to "AppCompatActivity"
maybe this will help someone.
Related Posts Related Posts :
  • Change Spinner DropDown width
  • Samsung Galaxy S4 Screen Size
  • Android text style missing light, medium, thin,
  • Android Studio gradle build failed for hello world app
  • Slide a layout up from bottom of screen
  • Play HTML5 video in iOS/Android native media player
  • How to rescale a bitmap file in android?
  • No view found for id 0x for fragment after rotation?
  • Define different themable styles to the same widget types
  • ProGuard not working in my app
  • FragmentTransaction from BaseAdapter
  • Connecting multiple devices in a Wifi Direct group
  • Why TabActivity is deprecated in android
  • How to capture low resolution picture using android camera
  • android preferenceactivity padding in landscape orientation
  • How can I store cookie in webview?
  • Passing variables from one activity to another
  • Create Multicolored Pie Chart in Android Studio
  • how to kill progress dialog in android
  • Show Error on the tip of the Edit Text Android
  • How do I use getWindowManager() by another java file
  • fetching images from gallery on android phones with internal storage
  • How to discover devices like Google TV and Nexus-Q using MediaRoute API on Android?
  • "Unfortunately your app stopped working"- Facebook Integration for Android
  • How to animate button in android?
  • Resource Not Found Exception in class without context or activity
  • Launching Android Netflix App And Passing Video Id
  • Making a Phone Call with a Number Extension
  • NullPointerException at BoringLayout.isBoring is anything but boring
  • java.lang.RuntimeException: Unable to get provider
  • Testing custom Views with Robolectric
  • tools:listheader doesn't work although tools:listitem does
  • oppo, vivo app kill notification not coming in android fcm
  • OnClick Method could not function correctly with if else statement
  • Best method to download image from url in Android
  • How can I open Drawer Layout moving all the view and not just slide over?
  • how to show profile pictures of friends in a list view?
  • Creating TimePickerDialog with custom style in Android
  • Android 2.3.6 support library v7 option menu is missing
  • need of vblank in Display subssytem
  • Android MP4 stream - Video cannot be played
  • FastAdapter: Undo button does not show up after swipe
  • What are reasons to pass getActivity as the LifecycleOwner to the LiveData's observe method in a fragment?
  • Implement Face Recognition in Android
  • Titanium studio cannot run "titanium" command in terminal
  • How to execute command line ffmpeg commands programatically in android?
  • Make Android List Items clickable with each item pointing to a different link
  • listview runs successfully, but nothing is display in emulator
  • How to zoom in a bitmap with high resolution?
  • Passing listView data through intent
  • Google map route direction show by arrows in android v2
  • how to start "uiautomator test run" from android code?
  • Proguard in Android Library
  • Alarm Clock from GIT - Gives error - Android
  • Mock injection using Mockito - Android
  • Get Bitmap from universal image loader
  • Unable to include custom font in android
  • Basics on using logcat in Android development
  • Android: Clear cache programmatically
  • Android: pass object without serialization
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org