Get Path from another app (WhatsApp) - android

I'm not getting Path from image or video from uri that I receive from whatsApp.
Uri comes like this: content://com.whatsapp.provider.media/item/16695
Media coming from Gallery, Downloads ands others are fine.
Anyone know how to get Path? This is the code I'm using:
public String getMediaPath(Context context, Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (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.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String[] column = { MediaStore.Images.Media.DATA };
final String[] projection = {
column[0]
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int index = cursor.getColumnIndexOrThrow(column[0]);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.contentprovider".equals(uri.getAuthority());
}
The result of this log:
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
is this:
Authority: com.whatsapp.provider.media, Fragment: null, Port: -1, Query: null, Scheme: content, Host: com.whatsapp.provider.media, Segments: [item, 16348]
And the cursor on getDataColumn looks like this:
>>>>> Dumping cursor
android.content.ContentResolver$CursorWrapperInner#1fc81ac
I/System.out: 0 {
I/System.out: }
I/System.out: <<<<<

You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path.
Using the code below
public static String getFilePathFromURI(Context context, Uri contentUri) {
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(TEMP_DIR_PATH + fileName+".jpg");
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Then IOUtils class is like below
public class IOUtils {
private static final int BUFFER_SIZE = 1024 * 2;
private IOUtils() {
// Utility class.
}
public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
int count = 0, n = 0;
try {
while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
out.write(buffer, 0, n);
count += n;
}
out.flush();
} finally {
try {
out.close();
} catch (IOException e) {
Log.e(e.getMessage(), e.toString());
}
try {
in.close();
} catch (IOException e) {
Log.e(e.getMessage(), e.toString());
}
}
return count;
}
}

you can try to this , then you get a bitmap of selected image and then you can easily find it's native path from Device Default Gallery.
Bitmap roughBitmap= null;
try {
// Works with content://, file://, or android.resource:// URIs
InputStream inputStream =
getContentResolver().openInputStream(uri);
roughBitmap= BitmapFactory.decodeStream(inputStream);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
float[] values = new float[9];
m.GetValues(values);
// resize bitmap if needed
Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);
string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
Java.IO.File file = new Java.IO.File(sdCardPath);
if (!file.Exists())
{
file.Mkdir();
}
var filePath = System.IO.Path.Combine(sdCardPath, name);
} catch (FileNotFoundException e) {
// Inform the user that things have gone horribly wrong
}

You can't get a path to file from WhatsApp. They don't expose it now. The only thing you can get is InputStream:
InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));
Using is you can show a picture from WhatsApp in your app.

You can also convert the URI to file and then to bytes if you want to upload the photo to your server.
Check out : https://www.stackoverflow.com/a/49575321

Using the code example below will return to you the bitmap :
BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/128752")))
After that you all know what you have to do.

It works for me for opening small text file... I didn't try in other file
protected void viewhelper(Intent intent) {
Uri a = intent.getData();
if (!a.toString().startsWith("content:")) {
return;
}
//Ok Let's do it
String content = readUri(a);
//do something with this content
}
here is the readUri(Uri uri) method
private String readUri(Uri uri) {
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(uri);
if (inputStream != null) {
byte[] buffer = new byte[1024];
int result;
String content = "";
while ((result = inputStream.read(buffer)) != -1) {
content = content.concat(new String(buffer, 0, result));
}
return content;
}
} catch (IOException e) {
Log.e("receiver", "IOException when reading uri", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e("receiver", "IOException when closing stream", e);
}
}
}
return null;
}
I got it from this repository https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java
I modified some code so that it work.
Manifest file:
<activity android:name=".MainActivity">
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
You need to add
#Override
protected void onCreate(Bundle savedInstanceState) {
/*
* Your OnCreate
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {
viewhelper(intent); // Handle text being sent
}
}

protected void onCreate(Bundle savedInstanceState) {
/*
* Your OnCreate
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {viewhekper(intent);//Handle text being sent}

Related

How to get content URI for Android 12 for document files(pdf, doc, word)?

Sorry for the long post.
I want to upload different types of files to our server from Android using API.
I am using the below code for file pick
Intent pickDocument = new Intent(Intent.ACTION_GET_CONTENT);
pickDocument.addCategory(Intent.CATEGORY_OPENABLE);
pickDocument.setType("*/*");
activity.startActivityForResult(Intent.createChooser(pickDocument, "ChooseFile"), requestCode);
And I am using the below class to get the file path from URI.
public class UriUtils {
private static Uri contentUri = null;
private static MimeTypeMap mimeType = MimeTypeMap.getSingleton();
#SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
// check here to is it KITKAT or new version
final boolean isKitKatOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
String fullPath = getPathFromExtSD(split);
if (fullPath != "") {
return fullPath;
} else {
return null;
}
} else if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
} finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
} else {
final String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
}
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
selection = "_id=?";
selectionArgs = new String[]{split[1]};
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
return getDataColumn(context, contentUri, selection, selectionArgs);
} else if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
return getMediaFilePathForN(uri, context);
} else {
return copyFromSource(uri, context);
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
private static boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
private static String getPathFromExtSD(String[] pathData) {
final String type = pathData[0];
final String relativePath = "/" + pathData[1];
String fullPath = "";
if ("primary".equalsIgnoreCase(type)) {
fullPath = Environment.getExternalStorageDirectory() + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
}
fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
return fullPath;
}
private static String getDriveFilePath(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getPath();
}
private static String getMediaFilePathForN(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getPath();
}
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 index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static String copyFromSource(Uri uri, Context context) {
ContentResolver contentResolver = context.getContentResolver();
String fileExtension = getFileExtension(uri, contentResolver);
String fileName = queryName(uri, contentResolver);
if (fileName == null)
fileName = getFileName(fileExtension);
// the file which will be the new cached file
File filePath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File outputFile = new File(filePath, fileName);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(outputFile);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return outputFile.getAbsolutePath();
}
#SuppressLint("Recycle")
private static String queryName(Uri uri, ContentResolver contentResolver) {
Cursor returnCursor = contentResolver.query(uri, null, null, null, null);
if (returnCursor == null)
return null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (nameIndex == -1)
return null;
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
private static String getFileExtension(Uri uri, ContentResolver contentResolver) {
return mimeType.getExtensionFromMimeType(contentResolver.getType(uri));
}
private static String getFileName(String fileExtension) {
return System.currentTimeMillis() + fileExtension + "";
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
private static boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
}
This code is working fine in Android 10 and below. But I am getting issue in Android 12
If I pick a file which is a document(doc, pdf, excel, txt) other than an image, video, and audio, I am getting path null.
In Android 12(Pixel 3), I got below URI
content://com.android.providers.media.documents/document/document%3A27958
So according to the above code, this is Media Document.
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
And If the file is media I am handling only 3 types of files
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
How to get contentUri if there are document files(doc, excel, pdf, txt)?
This is working for me.
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}else if ("document".equals(type)) {
uri = MediaStore.Files.getContentUri("external");
}
You can save your document files in an temp folder and return its address.
For example, Telegram messenger stores these types of files in this path:
Android\data\org.telegram.messenger\cache\sharing
Example for your code:
String tempPath = getPathFromUri(context, uri);
if (tempPath == null) {
tempPath = MediaController.copyFileToCache(uri, "file");
if (tempPath == null) {
showAttachmentError();
return;
}
}

While selecting a PDF file from recent files folder in Android 11 is giving NulllPointException:Uri

The below shows the way how I tried and it gives me NulllPointException: Uri While selecting a PDF file from the recent files folder in Android 11.
Please let me know How to get pdf file path from recent folder
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
//todo when permission is granted
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
startActivityForResult(intent, REQ_PDF);
} else {
//request for the permission
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
startActivityForResult(intent, REQ_PDF);
}
}
});
#SuppressLint({"SetTextI18n", "NewApi"})
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream = null;
try {
if (requestCode == REQ_PDF && resultCode == RESULT_OK && data != null) {
path = data.getData();
inputStream = this.getContentResolver().openInputStream(path);
byte[] pdfInBytes = new byte[inputStream.available()];
inputStream.read(pdfInBytes);
// Toast.makeText(getContext(), ""+value, Toast.LENGTH_SHORT).show();
String encodedCode = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
filePath = PathUtil.getPathFromUri(this, path);
// filePath= FileUtils.getPath(this,path);
if (filePath == null) {
// Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
SharedPrefMannager.showAlertDialog(InvoiceGenerationActivity.this, "Alert!", "Please select a file from internal storage", true);
} else {
file = new File(filePath);
file_size = Integer.parseInt(String.valueOf(file.length() / 1024));
}
tv_attachFile.setText("Change File");
tv_fileLocation.setVisibility(View.VISIBLE);
tv_fileLocation.setText(filePath);
//Toast.makeText(getContext(), encodedCode, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(InvoiceGenerationActivity.this, "Something went wrong " + e, Toast.LENGTH_SHORT).show();
}
}
public class PathUtil
{
private static Uri contentUri = null;
#SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
// check here to is it KITKAT or new version
final boolean isKitKatOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
final String type = split[0];
String fullPath = getPathFromExtSD(split);
if (fullPath != "") {
return fullPath;
} else {
return null;
}
//return getPathFromExtSD(split);
/* String fullPath =Environment.getExternalStorageState() + "/" + split[1];
if (fullPath != "") {
return fullPath;
} else {
return null;
}*/
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
} finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads",
"content://downloads/all_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
} else {
final String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.parseLong(id)); //public
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
} catch (NumberFormatException e) {
e.printStackTrace();
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}
// MediaProvider
else if (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.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("application".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; //MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
} else if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
return getMediaFilePathForN(uri, context);
} else {
return getDataColumn(context, uri, null, null);
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
private static boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
private static String getPathFromExtSD(String[] pathData) {
String type = pathData[0];
String relativePath = "/" + pathData[1];
String fullPath = "";
if ("primary".equalsIgnoreCase(type)) {
fullPath = getExternalStorageDirectory() + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
}
fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
if ((null == fullPath) || (fullPath.length() == 0)) {
fullPath = System.getenv("SECONDARY_SDCARD_STORAGE");
return fullPath;
}
/* if (fileExists(fullPath)) {
return fullPath;
}*/
fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
if ((null == fullPath) || (fullPath.length() == 0)) {
fullPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
return fullPath;
}
/* if (fileExists(fullPath)) {
return fullPath;
}*/
return fullPath;
}
private static String getDriveFilePath(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
InputStream inputStream = null;
FileOutputStream outputStream = null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
}
}
}
return file.getPath();
}
private static String getMediaFilePathForN(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
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 index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} catch (Exception e) {
// Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
private static boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
}
Any help would be appreciated. I am testing on an android R device. Why is it that when selecting the file from a RECENT section in the file browser I am not getting any file path meanwhile selecting the same file in the STORAGE section is returning file path?
I have added only that else part and it's working fine. thank you for helping. referece
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}else {
contentUri = MediaStore.Files.getContentUri("external");
}

Android variable at "onActivityResult" sometime null value on KITKAT

private void openCamera(int imageArray){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/SurveyDA/assets/images","absen_" +
System.currentTimeMillis() + ".jpg"));
Log.d("ddddd : ", String.valueOf(fileUri));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, imageArray);
}
when I want open camera, I set the fileuri, and Log success return uri
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
//getting bitmap object from uri
Log.d("ddddd : ", String.valueOf(fileUri));
bitmapImage[requestCode] = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fileUri);
// Initialize a new ByteArrayStream
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress the bitmap with JPEG format and quality 50%
bitmapImage[requestCode].compress(Bitmap.CompressFormat.JPEG,60,stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
bitmapImage[requestCode] = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false);
//displaying selected image to imageview
imageViews[requestCode].setImageBitmap(bitmapImage[requestCode]);
//calling the method uploadBitmap to upload image
} catch (IOException e) {
e.printStackTrace();
}
}else if(resultCode == Activity.RESULT_CANCELED) {
// User Cancelled the actiongetUriForFile
}
}
but in onActivityResult variable fileuri sometimes get null, and sometimes success return uri. And when I try in other phone Android 8.0.0, there no error.
how to fix that?
java.lang.RuntimeException: Unable to resume activity {com.example.surveyonlineda/com.example.surveyonlineda.Activity.AbsenActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.example.surveyonlineda/com.example.surveyonlineda.Activity.AbsenActivity}: java.lang.NullPointerException
Refer this Document for your issue you will get best solution
as I see, the fileUri is not returned by onActivityResult. You create it before start your cameraIntent. So in case your activity has been destroyed, the fileUri will null. To prevent it, I think you should use onSaveInstanceState to save the fileUri.
Here is an example to save the string fileUri
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of fileUri from saved state
fileUri = savedInstanceState.getString(FILE_URI);
} else {
// Probably initialize values for a new instance
}
}
#Override protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(FILE_URI, fileUri);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
You can try it. it worked for me
Step 1. Create class GetPathFromUri.class
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.*;
public class GetPathFromUri {
#SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
#SuppressLint("ObsoleteSdkInt") final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
if ("raw".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
if ("5D68-9217".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {}
}
// path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
// MediaProvider
else if (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.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
final String column = "_data";
final String[] projection = {column};
try (Cursor 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);
}
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static String getFileName(#NonNull Context context, Uri uri) {
String mimeType = context.getContentResolver().getType(uri);
String filename = null;
if (mimeType == null && context != null) {
String path = getPath(context, uri);
if (path == null) {
filename = getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Cursor returnCursor = context.getContentResolver().query(uri, null,
null, null, null);
if (returnCursor != null) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
return filename;
}
public static String getName(String filename) {
if (filename == null) {
return null;
}
int index = filename.lastIndexOf('/');
return filename.substring(index + 1);
}
public static File getDocumentCacheDir(#NonNull Context context) {
File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
logDir(context.getCacheDir());
logDir(dir);
return dir;
}
public static final String DOCUMENTS_DIR = "documents";
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
private static void logDir(File dir) {
if (!DEBUG) return;
Log.d(TAG, "Dir=" + dir);
File[] files = dir.listFiles();
for (File file : files) {
Log.d(TAG, "File=" + file.getPath());
}
}
#Nullable
public static File generateFileName(#Nullable String name, File directory) {
if (name == null) {
return null;
}
File file = new File(directory, name);
if (file.exists()) {
String fileName = name;
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
fileName = name.substring(0, dotIndex);
extension = name.substring(dotIndex);
}
int index = 0;
while (file.exists()) {
index++;
name = fileName + '(' + index + ')' + extension;
file = new File(directory, name);
}
}
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
logDir(directory);
return file;
}
private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
InputStream is = null;
BufferedOutputStream bos = null;
try {
is = context.getContentResolver().openInputStream(uri);
bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
byte[] buf = new byte[1024];
is.read(buf);
do {
bos.write(buf);
} while (is.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Step 2:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
String path = GetPathFromUri.getPath(this, data.getData())
Glide.with(this).load(path).into(imageView);
// Glide is library https://github.com/bumptech/glide
} catch (IOException e) {
e.printStackTrace();
}
}else if(resultCode == Activity.RESULT_CANCELED) {
// User Cancelled the actiongetUriForFile
}
}

File path in real device shows wrong path

In my class, I use the following method to get the file path, but it works only on the emulator; why?
My problem is with the real device (Samsung Galaxy j5):
The files in the internal hard:Encounter with Exception.
The files in the external hard: return a null path.
How can I fix this problem? The problem is in which part of my code.
UploaderActivity :
public class UploaderActictivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG ="MyPath" ;
private static final int REQUEST_CODE =10052 ;
Uri URI =null ;
private Button button;
private String path;
TextView messageText;
Button uploadButton,BrowsButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
ImageView imNotify;
JustifiedTextView js;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploader);
js=findViewById(R.id.textDes);
js.setText( getResources().getString(des) + "\n" +
getResources().getString(des1)+ "\n" +
getResources().getString(des2)+ "\n" +
getResources().getString(des3));
uploadButton = findViewById(R.id.upload);
BrowsButton = findViewById(R.id.browse);
BrowsButton.setOnClickListener(this);
uploadButton.setOnClickListener(this);
messageText =findViewById(R.id.messageText);
imNotify =findViewById(R.id.notify);
String msg=messageText.getText().toString();
if(msg.isEmpty()){
messageText.setVisibility(View.GONE);
imNotify.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
if(v==BrowsButton) {
showFileChooser();
}
if(v==uploadButton) {
//upload to site
if(path != null){
dialog = ProgressDialog.show(UploaderActictivity.this, "", "آپلود فایل، لطفاً صبر کنید...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
messageText.setText("در حال آپلود فایل...");
}
});
uploadFile(path);
}
}).start();
}
else{
Toast.makeText(UploaderActictivity.this,"ابتدا یک فایل انتخاب کنید!",Toast.LENGTH_SHORT).show();
}
}
}
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"انتخاب فایل..."),REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE) {
if (data == null) {
//no data present
return;
}
Uri currFileURI = data.getData();
path = FilePath.getPath(getApplicationContext(),currFileURI);
if(path != null && !path.equals("") ){
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
Log.i(TAG, "Selected File Path:" + path);
messageText.setText(path);
}else{
Toast.makeText(this,"شما قادر به آپلود محتوای فایل نیستید!",Toast.LENGTH_SHORT).show();
}
}
}
}
public int uploadFile(final String path) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final int UserID =prefs.getInt("UserID", 0);
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 5 * 1024 * 1024;
File sourceFile = new File(path);
String[] parts = path.split("/");
final String fileName = UserID + "_" + parts[parts.length-1];
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+path);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("محتوایی در این مسیر وجود ندارد!"
+path);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(AppConfig.upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "فايل مورد نظر آپلود شد." +
"\n" + getResources().getString(DescriptionForUpload)
;
messageText.setText(msg);
Toast.makeText(UploaderActictivity.this, "آپلود فايل کامل شد.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploaderActictivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
Toast.makeText(UploaderActictivity.this, "مشکلی رخ داده است!", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploaderActictivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
Toast.makeText(UploaderActictivity.this, "مشکلی رخ داده است!", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
FilePath class:
public class FilePath {
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
else if (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.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
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 index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
}
What you are trying to do is wrong to begin with.
Do not try to obtain a file system path.
You got a content uri. Use it to open an input stream. After that you can use the content as if you had opened a file input stream.

Convert file: Uri to File in Android

What is the easiest way to convert from an android.net.Uri object which holds a file: type to a java.io.File object in Android?
I tried the following but it doesn't work:
File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());
What you want is...
new File(uri.getPath());
... and not...
new File(uri.toString());
Notes
For an android.net.Uri object which is named uri and created exactly as in the question, uri.toString() returns a String in the format "file:///mnt/sdcard/myPicture.jpg", whereas uri.getPath() returns a String in the format "/mnt/sdcard/myPicture.jpg".
I understand that there are nuances to file storage in Android. My intention in this answer is to answer exactly what the questioner asked and not to get into the nuances.
use
InputStream inputStream = getContentResolver().openInputStream(uri);
directly and copy the file. Also see:
https://developer.android.com/guide/topics/providers/document-provider.html
After searching for a long time this is what worked for me:
File file = new File(getPath(uri));
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
Android + Kotlin
Add dependency for Kotlin Android extensions:
implementation 'androidx.core:core-ktx:{latestVersion}'
Get file from uri:
uri.toFile()
Best Solution
Create one simple FileUtil class & use to create, copy and rename the file
I used uri.toString() and uri.getPath() but not work for me.
I finally found this solution.
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtil {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private FileUtil() {
}
public static File from(Context context, Uri uri) throws IOException {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
String fileName = getFileName(context, uri);
String[] splitName = splitFileName(fileName);
File tempFile = File.createTempFile(splitName[0], splitName[1]);
tempFile = rename(tempFile, fileName);
tempFile.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (inputStream != null) {
copy(inputStream, out);
inputStream.close();
}
if (out != null) {
out.close();
}
return tempFile;
}
private static String[] splitFileName(String fileName) {
String name = fileName;
String extension = "";
int i = fileName.lastIndexOf(".");
if (i != -1) {
name = fileName.substring(0, i);
extension = fileName.substring(i);
}
return new String[]{name, extension};
}
private static String getFileName(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf(File.separator);
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
private static File rename(File file, String newName) {
File newFile = new File(file.getParent(), newName);
if (!newFile.equals(file)) {
if (newFile.exists() && newFile.delete()) {
Log.d("FileUtil", "Delete old " + newName + " file");
}
if (file.renameTo(newFile)) {
Log.d("FileUtil", "Rename file to " + newName);
}
}
return newFile;
}
private static long copy(InputStream input, OutputStream output) throws IOException {
long count = 0;
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
Use FileUtil class in your code
try {
File file = FileUtil.from(MainActivity.this,fileUri);
Log.d("file", "File...:::: uti - "+file .getPath()+" file -" + file + " : " + file .exists());
} catch (IOException e) {
e.printStackTrace();
}
EDIT: Sorry, I should have tested better before. This should work:
new File(new URI(androidURI.toString()));
URI is java.net.URI.
None of this works for me. I found this to be the working solution. But my case is specific to images.
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
With Kotlin it is even easier:
val file = File(uri.path)
Or if you are using Kotlin extensions for Android:
val file = uri.toFile()
UPDATE:
For images it return "Uri lacks 'file' scheme: content://"
Thanks for comment
One other way to reach that is create a Temporary File. to do that:
fun createTmpFileFromUri(context: Context, uri: Uri, fileName: String): File? {
return try {
val stream = context.contentResolver.openInputStream(uri)
val file = File.createTempFile(fileName, "", context.cacheDir)
org.apache.commons.io.FileUtils.copyInputStreamToFile(stream,file)
file
} catch (e: Exception) {
e.printStackTrace()
null
}
}
We use Apache Commons library FileUtils class. For adding it to your project:
implementation "commons-io:commons-io:2.7"
Note that MAKE SURE call to file.delete() after usage.
for more information checkout Documents.
If you have a Uri that conforms to the DocumentContract then you probably don't want to use File.
If you are on kotlin, use DocumentFile to do stuff you would in the old World use File for, and use ContentResolver to get streams.
Everything else is pretty much guaranteed to break.
#CommonsWare explained all things quite well. And we really should use the solution he proposed.
By the way, only information we could rely on when querying ContentResolver is a file's name and size as mentioned here:
Retrieving File Information | Android developers
As you could see there is an interface OpenableColumns that contains only two fields: DISPLAY_NAME and SIZE.
In my case I was need to retrieve EXIF information about a JPEG image and rotate it if needed before sending to a server. To do that I copied a file content into a temporary file using ContentResolver and openInputStream()
For this case, especially on Android, the way going for bytes is usually faster.
With this, I solved it by setting up a class FileHelper which is given the responsibility to deal with reading/writing bytes from/to file through stream and a class UriHelper which is given the responsibility to figure out path of Uri and permission.
As far as it's knew generally, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset) can help us to transfer string you want to bytes you need.
How to let UriHelper and FileHelper you to copy a picture noted by Uri into a file, you can run:
FileHelper.getInstance().copy(UriHelper.getInstance().toFile(uri_of_a_picture)
, FileHelper.getInstance().createExternalFile(null, UriHelper.getInstance().generateFileNameBasedOnTimeStamp()
+ UriHelper.getInstance().getFileName(uri_of_a_picture, context), context)
);
about my UriHelper:
public class UriHelper {
private static UriHelper INSTANCE = new UriHelper();
public static UriHelper getInstance() {
return INSTANCE;
}
#SuppressLint("SimpleDateFormat")
public String generateFileNameBasedOnTimeStamp() {
return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}
/**
* if uri.getScheme.equals("content"), open it with a content resolver.
* if the uri.Scheme.equals("file"), open it using normal file methods.
*/
//
public File toFile(Uri uri) {
if (uri == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
return new File(uri.getPath());
}
public DocumentFile toDocumentFile(Uri uri) {
if (uri == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
return DocumentFile.fromFile(new File(uri.getPath()));
}
public Uri toUri(File file) {
if (file == null) return null;
Logger.d(">>> file path:" + file.getAbsolutePath());
return Uri.fromFile(file); //returns an immutable URI reference representing the file
}
public String getPath(Uri uri, Context context) {
if (uri == null) return null;
if (uri.getScheme() == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
String path;
if (uri.getScheme().equals("content")) {
//Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
Logger.e("!!! cursor is null");
return null;
}
if (cursor.getCount() >= 0) {
Logger.d("... the numbers of rows:" + cursor.getCount()
+ "and the numbers of columns:" + cursor.getColumnCount());
if (cursor.isBeforeFirst()) {
while (cursor.moveToNext()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
}
} else {
cursor.moveToFirst();
do {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
} while (cursor.moveToNext());
}
path = uri.getPath();
cursor.close();
Logger.d("... content scheme:" + uri.getScheme() + " and return:" + path);
return path;
} else {
path = uri.getPath();
Logger.d("... content scheme:" + uri.getScheme()
+ " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
+ " and return:" + path);
return path;
}
} else {
path = uri.getPath();
Logger.d("... not content scheme:" + uri.getScheme() + " and return:" + path);
return path;
}
}
public String getFileName(Uri uri, Context context) {
if (uri == null) return null;
if (uri.getScheme() == null) return null;
Logger.d(">>> uri path:" + uri.getPath());
Logger.d(">>> uri string:" + uri.toString());
String path;
if (uri.getScheme().equals("content")) {
//Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
Logger.e("!!! cursor is null");
return null;
}
if (cursor.getCount() >= 0) {
Logger.d("... the numbers of rows:" + cursor.getCount()
+ "and the numbers of columns:" + cursor.getColumnCount());
if (cursor.isBeforeFirst()) {
while (cursor.moveToNext()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
}
} else {
cursor.moveToFirst();
do {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<cursor.getColumnCount(); i++) {
stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
stringBuilder.append("\n");
}
Logger.d(stringBuilder.toString());
} while (cursor.moveToNext());
}
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
cursor.close();
Logger.d("... content scheme:" + uri.getScheme() + " and return:" + path);
return path;
} else {
path = uri.getLastPathSegment();
Logger.d("... content scheme:" + uri.getScheme()
+ " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
+ " and return:" + path);
return path;
}
} else {
path = uri.getLastPathSegment();
Logger.d("... not content scheme:" + uri.getScheme() + " and return:" + path);
return path;
}
}
}
about my FileHelper:
public class FileHelper {
private static final String DEFAULT_DIR_NAME = "AmoFromTaiwan";
private static final int DEFAULT_BUFFER_SIZE = 1024;
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static final int EOF = -1;
private static FileHelper INSTANCE = new FileHelper();
public static FileHelper getInstance() {
return INSTANCE;
}
private boolean isExternalStorageWritable(Context context) {
/*
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
Logger.e("!!! checkSelfPermission() not granted");
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
private boolean isExternalStorageReadable(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
Logger.e("!!! checkSelfPermission() not granted");
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
#SuppressLint("SimpleDateFormat")
private String generateFileNameBasedOnTimeStamp() {
return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}
public File createExternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File dir ;
File file;
if (!isExternalStorageWritable(context)) {
Logger.e("!!! external storage not writable");
return null;
}
if (dir_name == null) {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
} else {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
}
Logger.d("... going to access an external dir:" + dir_path);
dir = new File(dir_path);
if (!dir.exists()) {
Logger.d("... going to mkdirs:" + dir_path);
if (!dir.mkdirs()) {
Logger.e("!!! failed to mkdirs");
return null;
}
}
if (file_name == null) {
file_path = dir_path + File.separator + generateFileNameBasedOnTimeStamp();
} else {
file_path = dir_path + File.separator + file_name;
}
Logger.d("... going to return an external dir:" + file_path);
file = new File(file_path);
if (file.exists()) {
Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
if (!file.delete()) {
Logger.e("!!! failed to delete file");
return null;
}
}
return file;
}
public File createInternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File dir ;
File file;
if (dir_name == null) {
dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
} else {
dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
}
dir_path = dir.getAbsolutePath();
Logger.d("... going to access an internal dir:" + dir_path);
if (!dir.exists()) {
Logger.d("... going to mkdirs:" + dir_path);
if (!dir.mkdirs()) {
Logger.e("!!! mkdirs failed");
return null;
}
}
if (file_name == null) {
file = new File(dir, generateFileNameBasedOnTimeStamp());
} else {
file = new File(dir, file_name);
}
file_path = file.getAbsolutePath();
Logger.d("... going to return an internal dir:" + file_path);
if (file.exists()) {
Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
if (!file.delete()) {
Logger.e("!!! failed to delete file");
return null;
}
}
return file;
}
public File getExternalFile(String dir_name, String file_name, Context context) {
String dir_path;
String file_path;
File file;
if (!isExternalStorageWritable(context)) {
Logger.e("!!! external storage not writable");
return null;
}
if (dir_name == null) {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
} else {
dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
}
if (file_name == null) {
file_path = dir_path;
} else {
file_path = dir_path + File.separator + file_name;
}
Logger.d("... going to return an external file:" + file_path);
file = new File(file_path);
if (file.exists()) {
Logger.d("... file exists:" + file.getAbsolutePath());
} else {
Logger.e("!!! file does't exist:" + file.getAbsolutePath());
}
return file;
}
public File getInternalFile(String dir_name, String file_name, Context context) {
String file_path;
File dir ;
File file;
if (dir_name == null) {
dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
} else {
dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
}
if (file_name == null) {
file = new File(dir.getAbsolutePath());
} else {
file = new File(dir, file_name);
}
file_path = file.getAbsolutePath();
Logger.d("... going to return an internal dir:" + file_path);
if (file.exists()) {
Logger.d("... file exists:" + file.getAbsolutePath());
} else {
Logger.e("!!! file does't exist:" + file.getAbsolutePath());
}
return file;
}
private byte[] readBytesFromFile(File file) {
Logger.d(">>> path:" + file.getAbsolutePath());
FileInputStream fis;
long file_length;
byte[] buffer;
int offset = 0;
int next = 0;
if (!file.exists()) {
Logger.e("!!! file doesn't exists");
return null;
}
if (file.length() > Integer.MAX_VALUE) {
Logger.e("!!! file length is out of max of int");
return null;
} else {
file_length = file.length();
}
try {
fis = new FileInputStream(file);
//buffer = new byte[(int) file_length];
buffer = new byte[(int) file.length()];
long time_start = System.currentTimeMillis();
while (true) {
Logger.d("... now next:" + next + " and offset:" + offset);
if (System.currentTimeMillis() - time_start > 1000) {
Logger.e("!!! left due to time out");
break;
}
next = fis.read(buffer, offset, (buffer.length-offset));
if (next < 0 || offset >= buffer.length) {
Logger.d("... completed to read");
break;
}
offset += next;
}
//if (offset < buffer.length) {
if (offset < (int) file_length) {
Logger.e("!!! not complete to read");
return null;
}
fis.close();
return buffer;
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}
public byte[] readBytesFromFile(File file, boolean is_fis_fos_only) {
if (file == null) return null;
if (is_fis_fos_only) {
return readBytesFromFile(file);
}
Logger.d(">>> path:" + file.getAbsolutePath());
FileInputStream fis;
BufferedInputStream bis;
ByteArrayOutputStream bos;
byte[] buf = new byte[(int) file.length()];
int num_read;
if (!file.exists()) {
Logger.e("!!! file doesn't exists");
return null;
}
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
bos = new ByteArrayOutputStream();
long time_start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - time_start > 1000) {
Logger.e("!!! left due to time out");
break;
}
num_read = bis.read(buf, 0, buf.length); //1024 bytes per call
if (num_read < 0) break;
bos.write(buf, 0, num_read);
}
buf = bos.toByteArray();
fis.close();
bis.close();
bos.close();
return buf;
} catch (FileNotFoundException e) {
e.printStackTrace();
Logger.e("!!! FileNotFoundException");
return null;
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}
/**
* streams (InputStream and OutputStream) transfer binary data
* if to write a string to a stream, must first convert it to bytes, or in other words encode it
*/
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}
public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}
/**
* io blocks until some input/output is available.
*/
public boolean copy(File source, File destination) {
if (source == null || destination == null) return false;
Logger.d(">>> source:" + source.getAbsolutePath() + ", destination:" + destination.getAbsolutePath());
try {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
byte[] buffer = new byte[(int) source.length()];
int len;
while (EOF != (len = fis.read(buffer))) {
fos.write(buffer, 0, len);
}
if (true) { //debug
byte[] copies = readBytesFromFile(destination);
if (copies != null) {
int copy_len = copies.length;
Logger.d("... stream read and write done for " + copy_len + " bytes");
}
}
return destination.length() != 0;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void list(final String path, final String end, final List<File> files) {
Logger.d(">>> path:" + path + ", end:" + end);
File file = new File(path);
if (file.isDirectory()) {
for (File child : file.listFiles()){
list(child.getAbsolutePath(), end, files);
}
} else if (file.isFile()) {
if (end.equals("")) {
files.add(file);
} else {
if (file.getName().endsWith(end)) files.add(file);
}
}
}
public String[] splitFileName(File file, String split) {
String path;
String ext;
int lastIndexOfSplit = file.getAbsolutePath().lastIndexOf(split);
if (lastIndexOfSplit < 0) {
path = file.getAbsolutePath();
ext = "";
} else {
path = file.getAbsolutePath().substring(0, lastIndexOfSplit);
ext = file.getAbsolutePath().substring(lastIndexOfSplit);
}
return new String[] {path, ext};
}
public File rename(File old_file, String new_name) {
if (old_file == null || new_name == null) return null;
Logger.d(">>> old file path:" + old_file.getAbsolutePath() + ", new file name:" + new_name);
File new_file = new File(old_file, new_name);
if (!old_file.equals(new_file)) {
if (new_file.exists()) { //if find out previous file/dir at new path name exists
if (new_file.delete()) {
Logger.d("... succeeded to delete previous file at new abstract path name:" + new_file.getAbsolutePath());
} else {
Logger.e("!!! failed to delete previous file at new abstract path name");
return null;
}
}
if (old_file.renameTo(new_file)) {
Logger.d("... succeeded to rename old file to new abstract path name:" + new_file.getAbsolutePath());
} else {
Logger.e("!!! failed to rename old file to new abstract path name");
}
} else {
Logger.d("... new and old file have the equal abstract path name:" + new_file.getAbsolutePath());
}
return new_file;
}
public boolean remove(final String path, final String end) {
Logger.d(">>> path:" + path + ", end:" + end);
File file = new File(path);
boolean result = false;
if (file.isDirectory()) {
for (File child : file.listFiles()){
result = remove(child.getAbsolutePath(), end);
}
} else if (file.isFile()) {
if (end.equals("")) {
result = file.delete();
} else {
if (file.getName().endsWith(end)) result = file.delete();
}
} else {
Logger.e("!!! child is not file or directory");
}
return result;
}
#TargetApi(Build.VERSION_CODES.O)
public byte[] readNIOBytesFromFile(String path) throws IOException {
Logger.d(">>> path:" + path);
if (!Files.exists(Paths.get(path), LinkOption.NOFOLLOW_LINKS)) {
Logger.e("!!! file doesn't exists");
return null;
} else {
return Files.readAllBytes(Paths.get(path));
}
}
#TargetApi(Build.VERSION_CODES.O)
public File writeNIOBytesToFile(String dir, String name, byte[] data) {
Logger.d(">>> dir:" + dir + ", name:" + name);
Path path_dir;
Path path_file;
try {
if (!Files.exists(Paths.get(dir), LinkOption.NOFOLLOW_LINKS)) {
Logger.d("... make a dir");
path_dir = Files.createDirectories(Paths.get(dir));
if (path_dir == null) {
Logger.e("!!! failed to make a dir");
return null;
}
}
path_file = Files.write(Paths.get(name), data);
return path_file.toFile();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return null;
}
}
#TargetApi(Build.VERSION_CODES.O)
public void listNIO(final String dir, final String end, final List<File> files) throws IOException {
Logger.d(">>> dir:" + dir + ", end:" + end);
Files.walkFileTree(Paths.get(dir), new FileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
Logger.d("... file:" + dir.getFileName());
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Logger.d("... file:" + file.getFileName());
if (end.equals("")) {
files.add(file.toFile());
} else {
if (file.endsWith(end)) files.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
Logger.d("... file:" + file.getFileName());
if (end.equals("")) {
files.add(file.toFile());
} else {
if (file.endsWith(end)) files.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
Logger.d("... file:" + dir.getFileName());
return FileVisitResult.CONTINUE;
}
});
}
/**
* recursion
*/
private int factorial (int x) {
if (x > 1) return (x*(factorial(x-1)));
else if (x == 1) return x;
else return 0;
}
}
For getting a file properly using a context uri,
Thanks to answers from #Mohsents , #Bogdan Kornev , #CommonsWare , #Juan Camilo Rodriguez Durán ;
I created an inputStream from uri and used this iStream to create a temporary file finally I am able to extract uri and path from this file.
fun createFileFromContentUri(fileUri : Uri) : File{
var fileName : String = ""
fileUri.let { returnUri ->
requireActivity().contentResolver.query(returnUri,null,null,null)
}?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
fileName = cursor.getString(nameIndex)
}
// For extract file mimeType
val fileType: String? = fileUri.let { returnUri ->
requireActivity().contentResolver.getType(returnUri)
}
val iStream : InputStream = requireActivity().contentResolver.openInputStream(fileUri)!!
val outputDir : File = context?.cacheDir!!
val outputFile : File = File(outputDir,fileName)
copyStreamToFile(iStream, outputFile)
iStream.close()
return outputFile
}
fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(4 * 1024) // buffer size
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
I made this like the following way:
try {
readImageInformation(new File(contentUri.getPath()));
} catch (IOException e) {
readImageInformation(new File(getRealPathFromURI(context,
contentUri)));
}
public static String getRealPathFromURI(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);
}
So basically first I try to use a file i.e. picture taken by camera and saved on SD card. This don't work for image returned by:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
That case there is a need to convert Uri to real path by getRealPathFromURI() function.
So the conclusion is that it depends on what type of Uri you want to convert to File.
After lots of searches and trying different approaches, I found this one working on different Android versions:
First copy this function:
fun getRealPathFromUri(context: Context, contentUri: Uri): String {
var cursor: Cursor? = null
try {
val proj: Array<String> = arrayOf(MediaStore.Images.Media.DATA)
cursor = context.contentResolver.query(contentUri, proj, null, null, null)
val columnIndex = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor?.moveToFirst()
return columnIndex?.let { cursor?.getString(it) } ?: ""
} finally {
cursor?.close()
}
}
And then, generate a file like this:
File(getRealPathFromUri(context, uri))
uri.toString() gives me: "content://com.google.android.apps.nbu.files.provider/1/file%3A%2F%2F%2Fstorage%2Femulated%2F0%2FDownload%2Fbackup.file"
uri.getPath() gives me: "/1/file:///storage/emulated/0/Download/backup.file"
new File(uri.getPath()) gives me "/1/file:/storage/emulated/0/Download/backup.file".
So if you have an access to file and want to avoid using ContentResolver or directly reading file, the answer is:
private String uriToPath( Uri uri )
{
File backupFile = new File( uri.getPath() );
String absolutePath = backupFile.getAbsolutePath();
return absolutePath.substring( absolutePath.indexOf( ':' ) + 1 );
}
Error handling is skipped to simplify the answer
Use this to write to file, It worked for me when uri of gif was provided by GBoard and I have to copy that gif in my app data.
try {
String destinationFilePath = getExternalFilesDir("gifs") + "/tempFile.txt";
InputStream inputStream = getContentResolver().openInputStream(uri);
OutputStream outputStream = new FileOutputStream(destinationFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
Some libraries are required File Objects for a process like a retrofit, some image editors e.t.c.
to convert URI to file object or anything similar we have a way which is to support all android old versions and upcoming versions.
Step 1:
You have to create a new file inside FilesDir which is nonreadable to other Apps with the same name as our file and extension.
Step 2:
You have to copy the content of the URI to create a file by using InputStream.
File f = getFile(getApplicationContext(), uri);
public static File getFile(Context context, Uri uri) throws IOException {
File destinationFilename = new File(context.getFilesDir().getPath() + File.separatorChar + queryName(context, uri));
try (InputStream ins = context.getContentResolver().openInputStream(uri)) {
createFileFromStream(ins, destinationFilename);
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
return destinationFilename;
}
public static void createFileFromStream(InputStream ins, File destination) {
try (OutputStream os = new FileOutputStream(destination)) {
byte[] buffer = new byte[4096];
int length;
while ((length = ins.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
}
private static String queryName(Context context, Uri uri) {
Cursor returnCursor =
context.getContentResolver().query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
Kotlin 2022
suspend fun Context.createFileFromAsset(assetName: String, fileName: String): File? {
return withContext(Dispatchers.IO) {
runCatching {
val stream = assets.open(assetName)
val file = File(cacheDir.absolutePath, fileName)
org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, file)
file
}.onFailure { Timber.e(it) }.getOrNull()
}
}
When done with the File make sure to call .delete() on it. Kudos to #Mohsent
For folks that are here looking for a solution for images in particular here it is.
private Bitmap getBitmapFromUri(Uri contentUri) {
String path = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
path = cursor.getString(columnIndex);
}
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(path);
return bitmap;
}
File imageToUpload = new File(new URI(androidURI.toString())); works if this is a file u have created in the external storage.
For example file:///storage/emulated/0/(some directory and file name)
By the following code, I am able to get adobe application shared pdf file as a stream and saving into android application path
Android.Net.Uri fileuri =
(Android.Net.Uri)Intent.GetParcelableExtra(Intent.ExtraStream);
fileuri i am getting as {content://com.adobe.reader.fileprovider/root_external/
data/data/com.adobe.reader/files/Downloads/sample.pdf}
string filePath = fileuri.Path;
filePath I am gettings as root_external/data/data/com.adobe.reader/files/Download/sample.pdf
using (var stream = ContentResolver.OpenInputStream(fileuri))
{
byte[] fileByteArray = ToByteArray(stream); //only once you can read bytes from stream second time onwards it has zero bytes
string fileDestinationPath ="<path of your destination> "
convertByteArrayToPDF(fileByteArray, fileDestinationPath);//here pdf copied to your destination path
}
public static byte[] ToByteArray(Stream stream)
{
var bytes = new List<byte>();
int b;
while ((b = stream.ReadByte()) != -1)
bytes.Add((byte)b);
return bytes.ToArray();
}
public static string convertByteArrayToPDF(byte[] pdfByteArray, string filePath)
{
try
{
Java.IO.File data = new Java.IO.File(filePath);
Java.IO.OutputStream outPut = new Java.IO.FileOutputStream(data);
outPut.Write(pdfByteArray);
return data.AbsolutePath;
}
catch (System.Exception ex)
{
return string.Empty;
}
}
you can use this function for get file from uri in new android and older
fun getFileFromUri(context: Context, uri: Uri?): File? {
uri ?: return null
uri.path ?: return null
var newUriString = uri.toString()
newUriString = newUriString.replace(
"content://com.android.providers.downloads.documents/",
"content://com.android.providers.media.documents/"
)
newUriString = newUriString.replace(
"/msf%3A", "/image%3A"
)
val newUri = Uri.parse(newUriString)
var realPath = String()
val databaseUri: Uri
val selection: String?
val selectionArgs: Array<String>?
if (newUri.path?.contains("/document/image:") == true) {
databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
selection = "_id=?"
selectionArgs = arrayOf(DocumentsContract.getDocumentId(newUri).split(":")[1])
} else {
databaseUri = newUri
selection = null
selectionArgs = null
}
try {
val column = "_data"
val projection = arrayOf(column)
val cursor = context.contentResolver.query(
databaseUri,
projection,
selection,
selectionArgs,
null
)
cursor?.let {
if (it.moveToFirst()) {
val columnIndex = cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)
}
cursor.close()
}
} catch (e: Exception) {
Log.i("GetFileUri Exception:", e.message ?: "")
}
val path = realPath.ifEmpty {
when {
newUri.path?.contains("/document/raw:") == true -> newUri.path?.replace(
"/document/raw:",
""
)
newUri.path?.contains("/document/primary:") == true -> newUri.path?.replace(
"/document/primary:",
"/storage/emulated/0/"
)
else -> return null
}
}
return if (path.isNullOrEmpty()) null else File(path)
}
public String getRealPathFromURI(Uri uri)
{
String result;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
result = uri.getPath();
cursor.close();
return result;
}
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
return result;
}
Then using to get file from URI :
File finalFile = newFile(getRealPathFromURI(uri));
--HOPE CAN HELP YOU----
Get the input stream using content resolver
InputStream inputStream = getContentResolver().openInputStream(uri);
Then copy the input stream into a file
FileUtils.copyInputStreamToFile(inputStream, file);
Sample utility method:
private File toFile(Uri uri) throws IOException {
String displayName = "";
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
try {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}finally {
cursor.close();
}
}
File file = File.createTempFile(
FilenameUtils.getBaseName(displayName),
"."+FilenameUtils.getExtension(displayName)
);
InputStream inputStream = getContentResolver().openInputStream(uri);
FileUtils.copyInputStreamToFile(inputStream, file);
return file;
}
Extension base on #Jacek Kwiecień answer for convert image uri to file
fun Uri.toImageFile(context: Context): File? {
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
val cursor = context.contentResolver.query(this, filePathColumn, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
val filePath = cursor.getString(columnIndex)
cursor.close()
return File(filePath)
}
cursor.close()
}
return null
}
If we use File(uri.getPath()), it will not work
If we use extension from android-ktx, it still not work too because
https://github.com/android/android-ktx/blob/master/src/main/java/androidx/core/net/Uri.kt
Add in onActivityResult, getting docx, or pdf file
var imageUriPath = ""
imageUriPath =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val split = (imageUri.path ? : "").split(":") //split the path.
split[1]
} else {
imageUri.path ? : ""
}
val file = File(imageUriPath)

Categories

Resources