Search code examples
androidandroid-imageandroid-sdcard

Image display from sd card


I am new to Android. In my app, I want to access a particular image from my sd card. But the image is not displayed. I have include WRITE_EXTERNAL_STORAGE request in my manifest.

public class Display extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display);

    final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
    final TextView name=(TextView) findViewById(R.id.name);
    final TextView phone_no=(TextView) findViewById(R.id.phone_no);

    File f= new File("/storage/sdcard0/Download/images.jpeg");
            Bitmap bMap = BitmapFactory.decodeFile(f.getAbsolutePath());
            imageView.setImageBitmap(bMap);
}

I also tried the following codes, but of no use

File mFichier = new File(Environment.getExternalStorageDirectory(),"/storage/sdcard0/Download/images.jpeg");

    if(mFichier.exists())
    {
        imageView.setImageURI(Uri.fromFile(mFichier));
    }

and also this code

Bitmap mBitmap = BitmapFactory.decodeFile("/storage/sdcard0/Download/images.jpeg"); 
imageView.setImageBitmap(mBitmap);

Please help me as to why my image is not getting displayed..


Solution

  • First of all, you want to load file from external storage like sdcard, you'd better use following code:

    public File getDataFolder(Context context) {
        File dataDir = null;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                dataDir = new File(Environment.getExternalStorageDirectory(), "myappdata");
                if(!dataDir.isDirectory()) {
                    dataDir.mkdirs();
                }
            }
    
            if(!dataDir.isDirectory()) {
                dataDir = context.getFilesDir();
            }
    
        return dataDir;
    }
    

    It will return a folder which is named "myappdata" located in your sd-card. After that, if you want to load a image from that folder, you can use following code:

    File cacheDir = getDataFolder(this);
    File cacheFile = new File(cacheDir, "images.jpeg");
    InputStream fileInputStream = new FileInputStream(cacheFile);
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = scale;
    bitmapOptions.inJustDecodeBounds = false;
    Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
    ImageView imageView = (ImageView)this.findViewById(R.id.preview);
    imageView.setImageBitmap(wallpaperBitmap);
    

    If you still have problem with above code, you can check the full example here:

    Android Save And Load Downloading File Locally