Search code examples
androidandroid-gallery

How to solve issue of path of any photo in gallery for kitkat and further versions?


I used this onActivityResult method to fetch photo from Gallery or camera

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0) {
            finish();
            photoFile = null;
            theftimage.setImageResource(R.drawable.camera);
        }
        if (requestCode == REQUEST_TAKE_PHOTO) {
            theftimage.setVisibility(View.VISIBLE);
            setPic();
    }

    if (requestCode == SELECT_PICTURE) {

            // Get the url from data
        if(resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                // Get the path from the Uri
                String path; //= getPathFromURI(selectedImageUri);
                path = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
                String filename=path.substring(path.lastIndexOf("/")+1);
                etFileName.setText(filename);
                Log.i(TAG, "Image Path : " + path);
                // Set the image in ImageView
                theftimage.setImageBitmap(BitmapFactory.decodeFile(path));

            }
        }
    }

}

and its method for fetching path

public String getPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return contentUri.getPath();
    }

error is

02-28 11:00:18.488: E/HAL(24576): hw_get_module_by_class: module name gralloc
02-28 11:00:18.488: E/HAL(24576): hw_get_module_by_class: module name gralloc

its giving me error of path in kitkat and further versions. Can you solve this? Help will be appriciated.


Solution

  • You do not need a path if all that you want is putting the selected file in a ImageView.

    One statement will do for all Android versions:

    theftimage.setImageBitmap(BitmapFactory.decodeStream(
        getContentResolver().openInputStream(data.getData())));