Invalid URI at getting path in different android api - android

Error:
FATAL EXCEPTION: main
Process: ua.romanpotapskiy.antihawk.prokaton, PID: 22721
java.lang.IllegalArgumentException: Invalid URI: file:///storage/emulated/0/Pictures/P/B/JPEG_20160115_170005_776674531.jpg
at android.provider.DocumentsContract.getDocumentId(DocumentsContract.java:752)
at ua.romanpotapskiy.antihawk.prokaton.RealPathUtil.getRealPathFromURI_API19(RealPathUtil.java:19)
at ua.romanpotapskiy.antihawk.prokaton.DeliverActivity.createImageFile(DeliverActivity.java:428)
at ua.romanpotapskiy.antihawk.prokaton.DeliverActivity.dispatchTakePictureIntent(DeliverActivity.java:298)
at ua.romanpotapskiy.antihawk.prokaton.DeliverActivity.onClick(DeliverActivity.java:248)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5258)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
My code:
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Prokaton/Big");
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
if (Build.VERSION.SDK_INT < 11)
mCurrentPhotoPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, Uri.fromFile(image));
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
mCurrentPhotoPath = RealPathUtil.getRealPathFromURI_API11to18(this, Uri.fromFile(image));
// SDK > 19 (Android 4.4)
else
mCurrentPhotoPath = RealPathUtil.getRealPathFromURI_API19(this, Uri.fromFile(image));
...
}
RealPathUtilClass :
public class RealPathUtil {
#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);
}
}
Im trying to use this exaple http://hmkcode.com/android-display-selected-image-and-its-real-path/
but i dont need this:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// 2. pick image only
intent.setType("image/*");
// 3. start activity
startActivityForResult(intent, 0);

try using this code inside your method, (use same code for all API versions)
Hope it will help you out
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor == null) {
result = uri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return result;

Related

In 4.4 Camera activity returns null

When i run this application on android 4.2, bitmap returns image, but in 4.4 it returns null........ In Gallery things works perfectly.
if (items[which].equals("Camera")) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
In onActivityResult
else if (requestCode == 1) {
final Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
if (imageNumber == 1)
slip_image1.setImageBitmap(thumbnail);
else if (imageNumber == 2)
slip_image2.setImageBitmap(thumbnail);
else if (imageNumber == 3)
slip_image3.setImageBitmap(thumbnail);
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
try { // FIXME NPE error when select image from QuickPic, Dropbox etc
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.INTERNAL_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;
} catch (Exception e) { // this is the fix lol
String result;
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = uri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
}
#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);
}

Select image from gallery for some device it null

i am getting image from gallery from below code
Uri filePath = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.MIME_TYPE};
Cursor cursor =
mCon.getContentResolver().query(filePath, filePathColumn, null, null, null);
but when i select image from file explore in some devices cursor is always null but if i select same image from gallery app it works... why it so ?
try this code
private String uriToFilename(Uri uri) {
String path = null;
if (Build.VERSION.SDK_INT < 11) {
path = RealPathUtil.getRealPathFromURI_BelowAPI11(this, uri);
} else if (Build.VERSION.SDK_INT < 19) {
path = RealPathUtil.getRealPathFromURI_API11to18(this, uri);
} else {
path = RealPathUtil.getRealPathFromURI_API19(this, uri);
}
return path;
}
create RealOathUtil.java
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri) {
Log.e("uri", uri.getPath());
String filePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
Log.e("wholeID", wholeID);
// Split at colon, use second item in the array
String[] splits = wholeID.split(":");
if (splits.length == 2) {
String id = splits[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();
}
} else {
filePath = uri.getPath();
}
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 in onactivtyResult() use this
Uri selectedImageUri = data.getData();
String selectedImagePath = uriToFilename(selectedImageUri);
You should try this.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Try this code.
To open gallery:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
mImagePath = getPath(selectedImageUri);
mBitmap = BitmapFactory.decodeFile(mImagePath);
mProfilePic.setImageBitmap(mBitmap);
}
}
To get actual path of image:
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Hope this may help you.

file path return null always in lollipop android

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();
}
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);
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.
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.
///////////////////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);
}
}
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;
}

how to get Real Path from Uri?

I would like to upload file to server. So I use a file chooser. But I have a problem with some application to get the real path from uri. the case if the content is a v
ideo, audio or image or if I can get the path directly i have no problem. the methode imlemented are :
public String getRealAudioPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Audio.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader(
this,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and it is the some for image and video. but my problem is when content is in this forme:
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fmnt%2Fsdcard%2FDownload%2Arbres.png
I tried the method
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
So how to get the real path from URi and if there is an other content type .
to get my real path is given below:
//Uri return from external activity
orgUri = data.getData();
text1.setText("fichier à envoyer " + orgUri.toString() + "\n");
// imagepath = orgUri.toString() ;
//path converted from Uri
//convertedPath = orgUri.getPath();
if(orgUri.toString().contains(IMAGEMEDIA)){
convertedPath = getRealPathFromURI(orgUri);
} else if(orgUri.toString().contains(AUDIOMEDIA)){
convertedPath = getRealAudioPathFromURI(orgUri);
}
else if(orgUri.toString().contains(VIDEOMEDIA)){
convertedPath = getRealvideoPathFromURI(orgUri);
}else {
if(orgUri.toString().contains("content")){
convertedPath = getFilePathFromContentUri(orgUri,
getApplicationContext().getContentResolver());
} else {
convertedPath = orgUri.getPath();
}
}
try this one
Uri selectedFile = data.getData();
String path = selectedFile.getPath();
it works for me.
if it is not than let me inform i have another way too
This works for me...
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >=
Build.VERSION_CODES.KITKAT;
Log.i("URI",uri+"");
String result = uri+"";
// DocumentProvider
// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isKitKat && (result.contains("media.documents"))) {
String[] ary = result.split("/");
int length = ary.length;
String imgary = ary[length-1];
final String[] dat = imgary.split("%3A");
final String docId = dat[1];
final String type = dat[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
} else if ("audio".equals(type)) {
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
dat[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
else
if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public 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;
}
It is a problem of decode. So the Solution is to add decode to the method. as given below:
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) throws UnsupportedEncodingException {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
String result = java.net.URLDecoder.decode(filePath, "UTF-8");
return result;
}
my onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//image.setImageBitmap(null);
//Uri return from external activity
orgUri = data.getData();
text1.setText("fichier à envoyer " + orgUri.toString() + "\n");
// imagepath = orgUri.toString() ;
//path converted from Uri
//convertedPath = orgUri.getPath();
if(orgUri.toString().contains(IMAGEMEDIA)){
convertedPath = getRealPathFromURI(orgUri);
} else if(orgUri.toString().contains(AUDIOMEDIA)){
convertedPath = getRealAudioPathFromURI(orgUri);
}
else if(orgUri.toString().contains(VIDEOMEDIA)){
convertedPath = getRealvideoPathFromURI(orgUri);
}else {
if(orgUri.toString().contains("content")){
try {
convertedPath = getFilePathFromContentUri(orgUri,
getApplicationContext().getContentResolver());
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
convertedPath = orgUri.getPath();
}
}
// text2.setText("Real Path: " + convertedPath + "\n");
imagepath = convertedPath;
uriFromPath = Uri.fromFile(new File(convertedPath));
}
}

How to get file path from uri?

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);

Categories

Resources