10

this is my code when i'm getting image from internal storage (gallery). In lollipop file path return always null.

if (requestCode == PICK_IMAGE)  {
        if(resultCode == RESULT_OK){
            //image successfully picked
            // launching upload activity
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            columnindex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            file_path = cursor.getString(columnindex);
            Log.d(getClass().getName(), "file_path"+file_path);
            fileUri = Uri.parse("file://" + file_path);
            cursor.close();
            launchUploadActivity(true, PICK_IMAGE);
        }else if (resultCode == RESULT_CANCELED) {
            // user cancelled recording
            Toast.makeText(getApplicationContext(),"User cancelled image  selection", Toast.LENGTH_SHORT).show();
        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),"Sorry! failed to pick image", Toast.LENGTH_SHORT).show();
        }
Gopal Singh
  • 1,133
  • 1
  • 9
  • 25

5 Answers5

28

Thanx all,I found the solution.

    Uri selectedImage = data.getData();
            String wholeID = DocumentsContract.getDocumentId(selectedImage);

            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];

            String[] column = { MediaStore.Images.Media.DATA };     

            // where id is equal to             
            String sel = MediaStore.Images.Media._ID + "=?";

            Cursor cursor = getContentResolver().
                                      query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                                      column, sel, new String[]{ id }, null);

            String filePath = "";

            int columnIndex = cursor.getColumnIndex(column[0]);

            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }   
            cursor.close();
            setImageFromIntent(filePath);
Gopal Singh
  • 1,133
  • 1
  • 9
  • 25
0

Add permission to your manifest -

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

you have to define read permission, before read any content.

EDITED

Update your code -

        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);

        columnindex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        file_path = cursor.getString(columnindex);
        Log.d(getClass().getName(), "file_path"+file_path);
        fileUri = Uri.parse("file://" + file_path);
        cursor.close();
        launchUploadActivity(true, PICK_IMAGE);

So here if any exception in getting data from cursor then it throws exception.

Ravi Bhandari
  • 4,682
  • 8
  • 40
  • 68
0

Lollipop decided to take another course with getting files from the system. (Some say it is from KitKat, but I haven't encountered it yet on KitKat). The code below is to get the filepath on lollipop

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(uri))
    {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;
        if ("image".equals(type)) 
        {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {
                split[1]
        };

        String filePath = getDataColumn(context, contentUri, selection, selectionArgs);
    }

isMediaDocument:

public static boolean isMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

getDataColumn:

private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
{
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst())
        {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

If you still have problems, this is the full answer that checks for images, audio, video, files, etc.

Community
  • 1
  • 1
Kevin van Mierlo
  • 9,554
  • 5
  • 44
  • 76
  • In lollipop images are also seen as documents. So getDocumentId retrieves the id of the image. This is used for getting type (in this case only images) and to get the right image back from the query (see getDataColumn -> selection). Here is the developers website with DocumentsContract: http://developer.android.com/reference/android/provider/DocumentsContract.html#getDocumentId(android.net.Uri) – Kevin van Mierlo Mar 20 '15 at 10:07
  • Can you print the uri and post it here? – Kevin van Mierlo Mar 20 '15 at 10:26
  • uri==>> content://com.android.providers.media.documents/document/image%3A13358 but i found the solution which work for me. i have posted that here. – Gopal Singh Mar 20 '15 at 10:31
  • thanks, this helped me, but i changed `MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;` to `MediaStore.Images.Media.EXTERNAL_CONTENT_URI;` because with `xx.audio.xxx` i was getting an MP3 file name while i have selected a photo, also i changed `Build.VERSION.SDK_INT >=` to `Build.VERSION.SDK_INT >` as kitkat was fine with my application – Yazan Feb 04 '16 at 12:43
0
///////////////////create file obj:
private File mFileTemp;

String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mFileTemp = new File(Environment.getExternalStorageDirectory(), InternalStorageContentProvider.TEMP_PHOTO_FILE_NAME);
        }
        else {
            mFileTemp = new File(getFilesDir(), InternalStorageContentProvider.TEMP_PHOTO_FILE_NAME);
        }
/////////////////// use in start activity for result
try {

                    InputStream inputStream = getContentResolver().openInputStream(data.getData());
                    FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
                    copyStream(inputStream, fileOutputStream);
                    fileOutputStream.close();
                    inputStream.close();

                     imagepath = mFileTemp.getPath();

                } catch (Exception e) {

                    Log.e("TAG", "Error while creating temp file", e);
                }
/////////////////
    public static void copyStream(InputStream input, OutputStream output)
            throws IOException 
            {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) 
        {
            output.write(buffer, 0, bytesRead);
        }
    }
benka
  • 4,732
  • 35
  • 47
  • 58
  • 2
    Please explain your code. While a purely code answer might get the asker's code working, it wont answer their question because they usually won't understand the solution. – SuperBiasedMan Jun 04 '15 at 09:27
0
public void String(Uri file_uri){
    String path = null;
    Cursor returnCursor = getContext().getContentResolver().query(file_uri, null, 
                             null, null, null);
    if (returnCursor != null && returnCursor.moveToFirst()) {
        //to get file name 
        int nameIndex = 
        returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        //string filename will get a filename which you have choosen
        String fileName = returnCursor.getString(nameIndex); 
        //to get full path of image
        path = returnCursor.getString(returnCursor.getColumnIndex(MediaStore.MediaColumns.DATA));
    }
    return path;

}
Zoe
  • 27,060
  • 21
  • 118
  • 148