There are some image files, and I want to get Uri of these image files. In my code, I only know path and file name of image files. How can I get Uri from its path and file name?
If you have a File
, you can always convert it to a URI
:
File file = new File(path + File.pathSeparator + filename);
URI uri = file.toURI();
Or, if you want to use the Android Uri class:
Uri uri = Uri.fromFile(file);
I had same question for my file explorer activity...but u should knw tht the contenturi for file only supports the mediastore data like image,audio and video....I am giving you for getting image content uri from selecting an image from sdcard....try this code...may be it will work for you...
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}