2

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");
        }
    }
Community
  • 1
  • 1
Shunan
  • 3,165
  • 6
  • 28
  • 48
  • That is not how you use a `Uri` from the `MediaStore`. Your code will fail on ~1 billion devices, if the image the user chooses is stored on removable storage. Please [use the `Uri` properly](https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html). – CommonsWare Sep 02 '16 at 16:15
  • Thanks @CommonsWare, i will go through your blog and change my code. – Shunan Sep 02 '16 at 16:24

1 Answers1

1

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.

Jason Leddy
  • 111
  • 6