Skip to content Skip to sidebar Skip to footer

Get Path To Image Chosen From Gallery(on Sd Card)

I simply CANNOT get the path to an image chosen from the gallery thats on the SD card, but there is no problem with images stored on the device. There are dozens of similar or dupl

Solution 1:

Apps do not have direct file access to any of the contents of the SD card. Therefore even if you could get a 'path' of some sort, your app would not have the ability to read anything from that location.

The only way to reliably access the contents of these files is through ContentResolver.openInputStream() (or the other open methods if you need an AssetFileDescriptor, etc).

You can most definitely copy the file to your own cache directory and then do whatever you want with the image.

Solution 2:

If you are using API 24, then you should use FileProvide, the official website of the introduction: https: //developer.android.com/reference/android/support/v4/content/FileProvider.html You should write like this:

  1. Specify a the contents of the storage area and path in XML, using child elements of the element. For example , The following pathsmann tells FileProvider that you intend to request content URIs for the images / subdirectory of your private file area.

    <Manifest>
        <Application>
            <Provider
                Android:name = "android.support.v4.content.FileProvider"
                Android:authorities = "com.mydomain.fileprovider"
                Android:exported = "false"
                Android:grantUriPermissions = "true"
               <Meta-data
               Android:name = "android.support.FILE_PROVIDER_PATHS"
               Android:resource = "@ xml / file_paths" />
            </ Provider>
        </ Application>
    </ Manifest>
    
    
    <? Xml version = "1.0" encoding = "utf-8"?><Resources>
        <Paths>
            <External-path
                Name = "external_files"
                Path = "." />
            <Root-path
                Name = "external_files"
                Path = "/ storage /" />
        </ Paths> `enter code here`
    </ Resources>
    
  2. The third step: file is your path

    UricontentUri= getUriForFile (getContext (), getPackageName () + ".provider", file);
    

Solution 3:

There are some different behaviors possessed by different phones. After a lot of research and trying different possibilities, I came up with a solution which is working on all phones on which I tested it (LG G2, Nexus 5, ZTE, Note 5, Nexus 6, Infinix Note 3 Pro and some others I don't remember). Try this if it works. Take according to your needs. It also includes capturing picture from camera, copy it and getting it's path.

//SELECT PICTURE FROM GALLERY OR CAPTURE FROM CAMERAprivatevoidselectPicture(View view) {
    tempView = view;
    final CharSequence[] items;
    if(view.getClass().getName().equalsIgnoreCase("android.widget.ImageView"))
            items = newCharSequence[]{ "Take Photo", "Choose from Library", "Remove Photo", "Cancel" };
    elseitems=newCharSequence[]{ "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builderbuilder=newAlertDialog.Builder(ActivityAddMemory.this);
    builder.setTitle("Add Image");
    builder.setItems(items, newDialogInterface.OnClickListener() {
        @OverridepublicvoidonClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                showCamera();
            } elseif (items[item].equals("Choose from Library")) {
                Intentintent=newIntent(
                        Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } elseif(items[item].equals("Remove Photo")) {
                imgLinearLayout.removeView(tempView);
                imagesList.remove(tempView.getId());
                if(imagesList.size() < 1) {
                    imgLinearLayout.setVisibility(View.GONE);
                }

                if(btnAddPhoto.getVisibility() == View.GONE)
                    btnAddPhoto.setVisibility(View.VISIBLE);
            } elseif (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}


//OPEN CAMERA IF WANT TO CAPTUREprivatevoidshowCamera() {

    try {
        Filefile=newFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DCIM");
        if (!file.exists()) {
            file.mkdirs();
        }

        FilelocalFile2=newFile(file + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        imageUri = Uri.fromFile(localFile2);

        IntentcameraIntent=newIntent("android.media.action.IMAGE_CAPTURE");

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            cameraIntent.setClipData(ClipData.newRawUri(null, Uri.fromFile(localFile2)));
        }

        startActivityForResult(cameraIntent, REQUEST_CAMERA);
    } catch (Exception localException) {
        Toast.makeText(ActivityAddMemory.this, "Exception:" + localException, Toast.LENGTH_SHORT).show();
    }
}


//GET PATH FROM URI IF SELECTED FROM GALLERYpublic String getRealPathFromURI(Uri uri){
    StringfilePath="";
    String[] filePahColumn = {MediaStore.Images.Media.DATA};
    Cursorcursor= getContentResolver().query(uri, filePahColumn, null, null, null);
    if (cursor != null) {
        if(cursor.moveToFirst()){
            intcolumnIndex= cursor.getColumnIndex(filePahColumn[0]);
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();
    }
    return filePath;
}


//DO WHAT YOU WANT WHEN RESULT IS RETURNED@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if(resultCode == RESULT_OK) {

        String path=null;
        Uri uri;

        if (intent == null || intent.getData() == null)
            uri = this.imageUri;
        elseuri= intent.getData();

        if(requestCode == SELECT_FILE) {
            path = getRealPathFromURI(uri);
        } elseif(requestCode == REQUEST_CAMERA){
            path = uri.getEncodedPath();
        }

        //THIS IS THE PATH YOU WOULD NEED

    }

}

Post a Comment for "Get Path To Image Chosen From Gallery(on Sd Card)"