Search code examples
androidandroid-cursor

Get the path of a file from other app


In my app I handle sharing of images/videos from other apps.

The problem is that if I want to handle the images from gallery it works great with following:

    Uri fileUri = (Uri) data.getParcelableExtra(Intent.EXTRA_STREAM);


    String[] projection = {MediaStore.MediaColumns.DATA};
    CursorLoader cursorLoader = new CursorLoader(mChatView.returnContext(), fileUri, projection, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();
    cursor.moveToFirst();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    File selectedImage = new File(cursor.getString(column_index));

I am getting the desired file which I want.

The problem is that is the image is shared via other app (Whatsapp/Fb Messenger) I am getting:

cursor == null

Example of Whatsapp URI:

fileUri = file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/Sent/IMG-20160616-WA0000.jpg

How can I access the file?

-Tested on Nexus 5 - Android v 6.0.1


Solution

  • Do it like this :

        String uri = data.getParcelableExtra(Intent.EXTRA_STREAM).toString();
    
        Uri fileUri = (Uri) data.getParcelableExtra(Intent.EXTRA_STREAM);
    
        File selectedImage;
    
        if (uri.startsWith("file://")) {
            selectedImage = new File(fileUri.getPath());
        } 
        else 
        {
            String[] projection = {MediaStore.MediaColumns.DATA};
            CursorLoader cursorLoader = new CursorLoader(mChatView.returnContext(), fileUri, projection, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            cursor.moveToFirst();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            selectedImage = new File(cursor.getString(column_index));
        }