Search code examples
androidcameraimageviewphotosd-card

Showing a photo from SD card to ImageView


I've been trying different things and I can save a photo in the SD card taken with Camera (not intent) but cannot pick up this same picture from SD card and place it in an ImageView. I get a Null pointer Exception allways.

Don't know what's missing, hope somebody can help me:

    PictureCallback jpegCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        // Save the image JPEG data to the SD card
        FileOutputStream fos = null;
        String fileName = "";
        try {
            fileName = "/mnt/sdcard/DCIM/MyPicture.jpg";
            fos = new FileOutputStream(fileName);
            fos.write(data);

            fos.close();
            Toast.makeText(getBaseContext(), "Image saved:" ,
                     Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            Log.e(TAG, "File Note Found", e);
            Toast.makeText(getBaseContext(), "Image couldn't be saved.",
                     Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            Toast.makeText(getBaseContext(), "Image couldn't be saved.",
                     Toast.LENGTH_LONG).show();
        }
        Bitmap bitmap = BitmapFactory.decodeFile(fileName);
        Log.d(TAG, fileName);
        mImageView.setImageBitmap(bitmap);
    }
};

I have tried that too:

    try {
        Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                + "/DCIM/MyPhoto.jpg");
        mImageView.setImageBitmap(picture);
    } catch (Exception e) {
        Log.e("Error reading file", e.toString());
    }
}

It saves the picture but goes to the catch when trying to put the image in the ImageView saying that "Error reading file"

logcat: enter image description here

DDMS: enter image description here

Sorry everybody for the headache... I forgot to put mImageView = (Imageview)findViewById(R.id.imageView1);

I'm a disaster :-)


Solution

  • Try this,

            try {
                Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
                Log.v("Path", Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
                mImageView.setImageBitmap(picture);
            } catch (Exception e) {
                Log.e("Error reading file", e.toString());
            }
    

    also check your imageview mImageView initialized or not