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
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));
}
Related
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
cursor.getString(columnIndex) Returns Null
Where as the selectedImage is not null.
Any suggestion on how I can create file from URI?
Cursor returns null when getting filepath from URI
A Uri is not a file. A Uri does not have to point to a file, let alone a file on the filesystem that you can access.
Any suggestion on how I can create file from URI?
Use ContentResolver and openInputStream() to get an InputStream on the content identified the Uri. Ideally, just use that InputStream directly. If, for some reason, you truly need a file:
Create a FileOutputStream on some file that you control (e.g., in getCacheDir())
Copy the bytes from the InputStream to the FileOutputStream
Use the file that you just created, deleting it when you are done
Use this method to get path:
public String getPath(Uri uri) {
// just some safety built in
if (uri == null) {
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
And in onACtivityResult use this:
Uri selectedImage = data.getData();
I'm saving an image loaded with Picasso to be shared afterwards. This is the code I'm using to save it:
String path = MediaStore.Images.Media.insertImage(
mContext.getContentResolver(), mImageBitmap, "Shared image", null);
return Uri.parse(path);
Now, when the image has been shared, I have to delete it using the URI. I've tried some answers I've seen here but none of them has worked. The image still appears in the gallery. These are the methods I have used:
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { new File(mImageUri.toString()).getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst())
{
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
contentResolver.delete(deleteUri, null, null);
}
c.close();
File file = new File(mImageUri.toString());
// This returns false
file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(mImageUri.toString()))));
Any idea of what i've done wrong?
Thanks,
Try this for deletion
String[] retCol = { MediaStore.Audio.Media._ID };
Cursor cur = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
retCol,
MediaStore.Images.Media.TITLE + "='"+TEMP_FILE_TITLE+"'", null, null
);
try {
if (cur.getCount() == 0) {
return;
}
cur.moveToFirst();
int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
Uri uri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id
);
int cnt = context.getContentResolver().delete(uri, null, null);
}finally {
cur.close();
}
In your case replace TEMP_FILE_TITLE = "Shared image"
I am trying to retrieve file path from URI. But my cursor is returning null.
Two problems:
Uri may be audio/ video. So how can I retrieve file path.
Why cursor is returning null?
Here is my code
String[] proj = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
//here cursor is null. So i am getting Null pointer exception
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
Permissions I have used:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
public void songList(){
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cur = contentResolver.query(uri, null, null, null, null);
if(cur.moveToFirst()){
do {
int pathIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
int nameIndex = cur.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
String spath = cur.getString(pathIndex);
String name = cur.getString(nameIndex);
paths.add(spath.substring(4));
songs.add(name);
} while (cur.moveToNext());
}
You can use get File path from diffrent SDk versions
Use RealPathUtils for it
public class RealPathUtils {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// 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 = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Now get the file Path from URI
String path = null;
if (Build.VERSION.SDK_INT < 11)
path = RealPathUtils.getRealPathFromURI_BelowAPI11(MainActivity.this, uri);
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
path = RealPathUtils.getRealPathFromURI_API11to18(MainActivity.this, uri);
// SDK > 19 (Android 4.4)
else
path = RealPathUtils.getRealPathFromURI_API19(MainActivity.this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
File file = new File(path);
I am trying to get an Image file from the gallery:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GET_IMAGE_FROM_GALLERY);
The message "Selecture Picture" is not shown as a Toast.
And in onActivityResult();
Uri selectedImageUri = data.getData(); //log shows proper URI
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
cursor.getString(column_index) returns Null.
I am testing it on Nexus 4.
EDIT:
Looks like this is a problem with Android 4.4, I have see other apps failing too.
Convert content:// URI to actual path in Android 4.4
Use this :
String selectedImagePath = null;
Uri selectedImageUri = data.getData();
Cursor cursor = activity.getContentResolver().query(
selectedImageUri, null, null, null, null);
if (cursor == null) {
selectedImagePath = selectedImageUri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
selectedImagePath = cursor.getString(idx);
}
how can I get the actual file path on the SD card where a content:// uri is pointing for an image?
I've adapted the code which #hooked82 linked to:
protected String convertMediaUriToPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
Content URIs have syntax content://authority/path/id, read here.
Parse id from content URI and query MediaStore.Images.Media.EXTERNAL_CONTENT_URI as follows:
long id = ContentUris.parseId(Uri.parse(contentUri));
Cursor cursor = getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{ MediaStore.Images.Media.DATA },
MediaStore.Images.Media._ID + " = ?", new String[]{ Long.toString(id) },
null);
if (cursor.moveToNext()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();