Shunan
Shunan

Reputation: 3254

Issue in fetching image from SD card and displaying on an ImageView

I found a program on this page to fetch image from sd card and show it on an imageView. I am getting issue at this line -

bitmap = BitmapFactory.decodeFile(picturePath);

I am getting correct value of picturePath variable but in the above line it is setting bitmap value as null. I had visited various threads and almost everyone is using this same line. I am not getting what is wrong with my code

Here is my complete code -

    private Button upload;
    ImageView imgView;
    EditText caption;
    Bitmap bitmap;

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

        imgView = (ImageView) findViewById(R.id.imageView);

        upload = (Button) findViewById(R.id.Upload);
        caption = (EditText) findViewById(R.id.caption);
        imgView.setImageResource(R.drawable.ic_menu_gallery);
        upload.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, 2);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 2 && resultCode == RESULT_OK
                && null != data) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            bitmap = BitmapFactory.decodeFile(picturePath);
            imgView.setImageBitmap(bitmap);
            caption.setText("Hello");
        }
    }

Upvotes: 2

Views: 26

Answers (1)

Jason Leddy
Jason Leddy

Reputation: 111

Try putting this in your AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

After that, make sure you have the permission enabled in the App Info screen on your device.

Upvotes: 1

Related Questions