get a file object from google drive with URI android - java

I have tried numerous methods of getting a file object from a google drive URI but most result in the following error:
java.lang.SecurityException: Permission Denial: reading com.google.android.apps.docs.storagebackend.StorageBackendContentProvider uri content://com.google.android.apps.docs.storage/document/acc=1;doc=4235 from pid=32140, uid=10149 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
So I added android.permission.MANAGE_DOCUMENTS and it did not work, so I tried to use grantUriPermission() and got the following error:
java.lang.SecurityException: Uid 10151 does not have permission to uri 0 # content://com.google.android.apps.docs.storage/document/acc=1;doc=4235
This file plugin has a nice way of getting files from just about anywhere, except google drive: aFileChooser.
So I took to stack overflow for answers:
Open a Google Drive File Content URI after using KitKat Storage Access Framework
Android KitKat securityException when trying to read from MediaStore
Getting Permission Denial Exception
No permission for UID to access URI error on Android Application
and there are about 15 others, but none helped
I am using Cordova so this is a cross platform app so it restricts me a bit. Here is how I get my URI, I press a button in my webview app, and then a new page is loaded allowing me to select my video from somewhere on my phone and I select google drive, then select a video, and then a URI is sent back to my webview I was on, I then send the URI to a java file to try and download the file. here is the different methods I have tried to download the file:
String filePath = null;
Log.d(TAG,"URI = "+ uri);
if (uri != null && "content".equals(uri.getScheme())) {
Log.d(TAG, "got inside if");
Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Files.FileColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
Log.d(TAG, "got inside else");
filePath = uri.getPath();
}
Log.d("","Chosen path = "+ filePath);
This method is similar, but fails the same:
String mimeType = context.getContentResolver().getType(uri);
Log.d(TAG,mimeType);
Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
Log.d(TAG,returnCursor.getString(nameIndex));
Log.d(TAG,Long.toString(returnCursor.getLong(sizeIndex)));
This method game the same error as the previous
try{
InputStream input = context.getContentResolver().openInputStream(uri);
try {
File file = new File(context.getCacheDir(), "cacheFileAppeal.mp4");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace(); // handle exception, define IOException and others
}
} finally {
input.close();
}
}
catch(Exception e){
e.printStackTrace();
}
all three game me
java.lang.SecurityException: Permission Denial: reading com.google.android.apps.docs.storagebackend.StorageBackendContentProvider uri content://com.google.android.apps.docs.storage/document/acc=1;doc=4235 from pid=32140, uid=10149 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
The following code for some reason did not crash, but gave me the mimeType:
String mimeType = context.getContentResolver().getType(uri);
I think the problem is that I am not using the URI in the original intent where the URI was retrieved from google drive, but I am not sure.
Does anyone know how to get a file object from google drive URI?

Related

Android 11 open failed: EACCES (Permission denied)

I am developing an app. In which I am uploading different file types (e.g. docx, pdf, zip) to a WAMP Server. Below is path of file to my internal Storage.
/storage/emulated/0/WhatsApp/Media/WhatsApp Documents/api.txt
I have added and allowed storage permission in Manifest file and also on runtime for reading a file. However there is no Internal Storage Permission request available.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and also for Android 10 I was using this attribute also
android:requestLegacyExternalStorage="true"
But I am getting this error on Android 11 OS a.k.a Android R onboard Samsung Galaxy when I am reading file from Internal Storage for uploading.
java.io.FileNotFoundException: /storage/emulated/0/WhatsApp/Media/WhatsApp Documents/api.txt: open failed: EACCES (Permission denied)
On An Android 11 device your app only has access to its own files.
And to general mediafies in public directories.
Try to list the files in that whatsapp directory and you will see that
they are not listed.
You have two options to read the file.
Let the user pick the file with ACTION_OPEN_DOCUMENT. Request
MANAGE_EXTERNAL_STORAGE in manifest and let the user confirm.
Ordinary request is not working for the MANAGE_EXTERNAL_STORAGE permission. This permission must be set in Android setting by user.
You can try to use the android:preserveLegacyExternalStorage="true" tag in the manifest file in the application tag. This tag is used to access the storage in the android 11 devices. And for more detail follow this link it will explain you more as per your requirement.
I search a lot of time and get the solution that adds <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/> in the manifest file and try to get the file access permission in the android 11 phones. Then you will open and read the file from the storage.
But the thing is that the play store does not allow you to use of the MANAGE_EXTERNAL_STORAGE permission in your app. it will take time to give access to the developer to use it to access all the files.
Here the link is
For Android 11 or above use the code below on the onCreate() of the activity. It will run once and ask for permission.
if (Build.VERSION.SDK_INT >= 30){
if (!Environment.isExternalStorageManager()){
Intent getpermission = new Intent();
getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(getpermission);
}
}
Next declare the MANAGE_EXTERNAL_STORAGE permission in the manifest.
However, the problem with this method is that you cannot upload it to play store if you don't have a good reason on why you need access to all files.
On An Android 11 device your app only has access to its own files.
And to general mediafies in public directories.
Try to list the files in that whatsapp directory and you will see that they are not listed.
You have two options to read the file.
Let the user pick the file with ACTION_OPEN_DOCUMENT.
Request MANAGE_EXTERNAL_STORAGE in manifest and let the user confirm.
Try to get path with this method.....
public static String getDriveFile(Context context, Uri uri) {
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);
}
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();
}
I worked on Android application based on Cordova and I had to change the version the application was focused on to save files in the device.
I change the API Level version to 28 and works correctly. This change is used to avoid the scoped storage feature added on Android 10.
This information is extracted from this page:
https://developer.android.com/training/data-storage/use-cases#opt-out-scoped-storage
I hope this information is helpful.
First, check whether you have implemented scoped storage logic in-app.
You can also use android:requestLegacyExternalStorage="true"
But this legacyStoragePermission is limited to version 10.
You need to implement scoped logic.
Also, check whether your targetSDKVersion value is 30 or greater or not,
this is needed if you are using the app in Device android version 30 or more.
I spent a week getting the info on how to read files from External storage on Android 11 API 29 and Later.
You still need Manifest permission READ_EXTERNAL_STORAGE.
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Open a specific media item using ParcelFileDescriptor.
ContentResolver resolver = getApplicationContext()
.getContentResolver();
// "rw" for read-and-write;
// "rwt" for truncating or overwriting existing file contents.
String readOnlyMode = "r";
// uri - I have got from onActivityResult
//uri = data.getData();
ParcelFileDescriptor parcelFile = resolver.openFileDescriptor(uri, readOnlyMode);
FileReader fileReader = new FileReader(parcelFile.getFileDescriptor());
BufferedReader reader = new BufferedReader(fileReader);
String line;
while ((line = reader.readLine()) != null) {
//Your action here!!!
}
reader.close();
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
Read this: Open a media file.
from android 10, it is not possible to access all the files through your app,
so while saving data for example image , use following code and then you can read it normally. getExternalFilesDir is important
File file=new File(getActivity().getApplicationContext().getExternalFilesDir(null),"/scantempo"+"/Image_" + System.currentTimeMillis() + ".jpg");
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Uri uri=Uri.fromFile(file);
return uri;
After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.
For read files from external storage following codes:
fun startFilePicker(activity: Activity, requestCode: Int) {
val pickIntent: Intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
type = "*/*"
}
activity.startActivityForResult(pickIntent, requestCode)
}
override fun onActivityResult(requestCode : Int , resultCode : Int , data : Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fileUri=data.data
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
context.contentResolver.takePersistableUriPermission(
fileUri,
takeFlags
)
}
Create temp file
fun createTempFileForUpload(context:Context,fileUri:Uri){
val docFile = DocumentFile.fromSingleUri(context, fileUri)
val fileName: String = if (docFile == null || docFile.name.isNullOrBlank()) {
FilenameUtils.getName(fileUri.path)
} else {
docFile.name!!
}
val tempFile = File.createTempFile("tempFile", "tmp")
val ins: InputStream = context.contentResolver.openInputStream(fileUri)!!
val out: OutputStream = FileOutputStream(tempFile)
val buf = ByteArray(1024)
var len: Int = ins.read(buf)
while (len > 0) {
out.write(buf, 0, len)
len = ins.read(buf)
}
out.close()
ins.close()
tempFile.mkdirs()
}
Then you can upload temp file .
You can change allowBackup from true to false in Manifest's application part. It worked for me.
android:allowBackup="false"

Why is ALBUM_ART the only field that returns null from MediaStore when others are fine?

I'm having trouble retrieving the album artwork path. My storage permissions can't be the problem since I can fetch all other fields, so I'm wondering what the problem might be. I'll admit I'm a bit new to ContentResolvers and the MediaStore. I just need a path to be used in BitmapFactory.decodeFile(). The code is below, followed by the Log output.
Context (if it helps)
- Method is called from SongRoomDatabase.java (not an activity) which extends RoomDatabase.
- The context is passed from the MainActivity to the DB through the DB constructor.
Test method for retrieving album data from ALBUM_ID = 209 ("Viva la Gloria!" by Greenday)
public static void getCoverArtTest(){
Cursor cursor = mContext.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] {
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ALBUM_ART,
MediaStore.Audio.Albums.ARTIST
},
MediaStore.Audio.Albums._ID+ "=?",
new String[] {String.valueOf(209)},
null);
if (cursor != null && cursor.moveToFirst()) {
String path = "";
path += cursor.getString(0) + "/";
path += cursor.getString(1) + "/";
path += cursor.getString(2) + "/";
path += cursor.getString(3) + "/";
// do whatever you need to do
Log.d("artworkTag", "Album art path: " + path);
}
}
Output
Album art path: 209/21st Century Breakdown/null/Green Day/
Is it just stored somewhere else? Do I need to retrieve it a specific way since it's not a string like the other fields (if it's returning something other than it's path)?
I noticed recently in my app the album arts started coming up empty where it had previously worked with similar code.
I checked the developer reference and there is new information about ALBUM_ART
This constant was deprecated in API level 29. Apps may not have
filesystem permissions to directly access this path. Instead of trying
to open this path directly, apps should use
ContentResolver#loadThumbnail to gain access.
So I tried changed the targetSdkVersion version back to 28 but still no good when running on a device with android 10 Q which is api 29.
So unfortunately to support newer androids we need to use something like this instead:
String filePath = null;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
Cursor albumCursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Media._ID + " = " + albumId,
null,
null);
if (albumCursor != null) {
if (albumCursor.moveToFirst()) {
filePath = albumCursor.getString(1);
}
albumCursor.close();
}
} else {
Uri albumArtUri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, Long.parseLong(albumId));
try {
Bitmap bitmap = context.getContentResolver().loadThumbnail(albumArtUri, new Size(1024, 1024), null);
File art = new File(context.getCacheDir(), "albumart" + albumId + ".jpg");
art.createNewFile();
FileOutputStream fos = new FileOutputStream(art);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
filePath = art.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
}

Android couldn't able to write and delete operation on sd card

I am working now on ImageCompressor app.
I need to delete and write (update) image file. In Internal storage works perfectly but **SD Card can't give me access to Delete and Write files.
How can my app able to do write and delete operation on sd card (removable storage)?
I've already done whole project without this, so I have to must find a way.
Update:
I am already research & discuss about this issue. And understood I have to use storage access framework But I'm new on SAF.
I used a library to compress photo that need File not Uri. For that I do Uri -> File and use Intent.ACTION_OPEN_DOCUMENT and pick image from Removable storage.
But for removable storage I can't find Image Real Path from uri.
I don't know it's the right way or not. If there have any way in SAF where I can Compress my Image using uri, let me know. Or How to get Image real path from uri of Removable Storage Photo.
Update code SAF:
// ----------- Intent -------------
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
// ------------ On Activity Result --------------
Uri uri = data.getData();
try {
ParcelFileDescriptor fileDescriptor = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fos = new FileOutputStream(fileDescriptor.getFileDescriptor());
FileInputStream fis = new FileInputStream(getImageFilePath(uri));
FileChannel source = fis.getChannel();
FileChannel destination = fos.getChannel();
destination.transferFrom(source, 0, source.size());
fis.close();
fos.close();
fileDescriptor.close();
Toast.makeText(this, "File save successfully.", Toast.LENGTH_SHORT).show();
}
Uri to File Path, I done where pick image from media apps(like Gallary, Photos) But pick from sd card what will instead of MediaStore.Images.Media.DATA I don't know. Code:
private File getImageFilePath(Uri uri) throws IOException {
String image_id = null, imagePath = null;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
image_id = cursor.getString(0);
image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
cursor.close();
}
cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
}
File file = new File(imagePath);
return new Compressor(this).setQuality(50).compressToFile(file);
}
Removable SD cards are write only on modern Android devices if you use File and FileOutputStream classes.
If you are lucky then your device using getExternalFilesDirs() returns as second item an app specific directory on the card where you still can write.
For the rest and instead use the Storage Access Framework.
Start with letting the user choose the sd card with Intent.ACTION_OPEN_DOCUMENT_TREE or a file with Intent.ACTION_OPEN_DOCUMENT.
I digged into an old Android app of mine and retrieved this :
This method convert the root of the sdcard uri, to a File path.
public File getRootPath(Context context, Uri sdcardRootUri)
{
List<String> pathSegments = sdcardRootUri.getPathSegments();
String[] tokens = pathSegments.get(pathSegments.size()-1).split(":");
for (File f : ContextCompat.getExternalFilesDirs(context, null))
{
String path = f.getAbsolutePath().substring(0, f.getAbsolutePath().indexOf("/Android/"));
if (path.contains(tokens[0]))
{
return new File(path);
}
}
return null;
}
And in order to retrieved the uri of the sdcard root, I used that :
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, SDCARD_ROOT_CODE);
Then the user would choose the root of the sdcard and then, I handled the result like this :
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK && requestCode == SDCARD_ROOT_CODE)
{
// Persist access permissions
Uri sdcdardRootUri = data.getData();
grantUriPermission(getPackageName(), sdcdardRootUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(sdcdardRootUri, takeFlags);
// Do whatever you want with sdcdardRootUri
}
}
I hope it's what you are looking for. With that you can read/write/delete any file you want on the sdcard.
you have try
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
//Filter common Linux partitions
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("media"))
continue;
if (line.contains("system") || line.contains("cache")
|| line.contains("sys") || line.contains("data")
|| line.contains("tmpfs") || line.contains("shell")
|| line.contains("root") || line.contains("acct")
|| line.contains("proc") || line.contains("misc")
|| line.contains("obb")) {
continue;
}
if (line.contains("fat") || line.contains("fuse") || (line
.contains("ntfs"))) {
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
String path = columns[1];
if (path!=null&&!SdList.contains(path)&&path.contains("sd"))
SdList.add(columns[1]);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Transferring a File in android

I have been struggling for two days to try and understand the process of copying a file to the SD card in Android. None of the methods I tried thus far seem to work.
My application has a Profile Picture setting. I need to launch an Intent to pick an Image, then I need to copy the Image to a new Path on the SD Card and then return the Uri of the new Image at which point I check the Images Orientation (Samsung Pics seem to be rotated 90 degrees sometimes). I then rotate the Image correctly and then save the Uri to a SharedPreferences File for use in the Application.
This is my Intent Call:
case R.id.ib_userImage:
i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
break;
This is my current horrific attempt at the copy function, I have changed it so much I am not very lost.
public static void copyImage(Context context, Uri uri) {
Log.i("ATTENTION", "Inside the Copy Function");
Log.i("ATTENTION", "Trying to copy file: " + uri.toString());
try {
String outputPath = Environment.getExternalStorageDirectory() + "/appname/images/";
File dir = new File(outputPath);
if(!dir.exists()) {
dir.mkdirs();
}
Log.i("ATTENTION", "Destination File Created at: " + dir.toURI().toString());
InputStream in = context.getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(dir);
byte[] buffer = new byte[1024];
while(in.read(buffer) > 0) {
out.write(buffer);
}
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("ATTENTION", "File Copied");
}
Thank you for the help, I will provide any other information you might need.
Update:
I am now getting the Following Exception During the Write Process
java.io.FileNotFoundException: /storage/emulated/0/appname/images: open failed: EISDIR (Is a Directory);
My Understaing is that I specified a Directory with the following code:
String outputPath = Environment.getExternalStorageDirectory() + "/medinfo/images/";
File dir = new File(outputPath);
if(!dir.exists()) {
dir.mkdirs();
}
and then passed it to the OutputStream:
OutputStream out = new FileOutputStream(dir);
and the OutputStream would create the file for me within that Directory.
I didn't think that was actually trying to open the Directory.
Usual problem. Don't ignore the count returned by read().
while ((count = in,read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
EDIT Your directory problem is cured by:
dir.getParentFile().mkdirs();
and removing the redundant existence check. At present you are creating the file itself as a directory.

Move and rename file in android

I am trying to copy a file to another folder in the android, but so far, i got no success. I manage to do so with a selected image and when taking a photo, but not with files.
I've read and tried several solutions passed by the community (searched over the forum and the internet), but none of it was able to solve my problem when copying.
First things first. I added the permissions to my manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
after that, before copying a file, i print its filepath and the directory file path:
06-10 11:11:11.700: I/System.out(1442): /mimetype/storage/sdcard/Misc/Javascript erros for Submit and Plan buttons in IE.doc
06-10 11:11:11.710: I/System.out(1442): /storage/sdcard/files/queue
both exists:
to copy the file to the expected folder I used the FileUtils:
try {
FileUtils.copyFile(selectedFile, dir);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem is: I get no exception and the file isn't there. I tried this solution either:
How to move/rename file from internal app storage to external storage on Android?
same thing, no exception, but no file either.
**Edited**
This is how I get the file.
Uri uri = data.getData();
File selectedFile = new File(uri.getPath());
File dir = new File(Environment.getExternalStorageDirectory(), "files/queue");
To get the image, I do this way:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
saveChecklistImage(BitmapFactory.decodeFile(picturePath));
I retrieve the file here when I call BitmapFactory.decodeFile(picturePath), then, I save it without a problem.
Should file follow this standard as well?
**Solution**
I found out a way to do so in this post:
android get real path by Uri.getPath()
Specifically this method:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
kind of same thing i was doing with image, but in a much smarter way ;D
easier than I tought.
Thanks for the helpers
If argument 2 is a directory you should be using copyFileToDirectory.
copyFile() doesn't take directory as a 2nd parameter (see here). It takes file (as source) and file (as destination). Create an empty file first:
File file = new File(dir+"/newfile.doc");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Use that instead of dir. Or use Travis' way. Also replace [space] with _ in your filenames.

Categories