Android - Not being able to retrieve file from external Share Button - android

I'm trying to retrieve the file that the user wants to share via, for example, the Photo Gallery App. So, when they tap on the share button, and select my application, I'm retrieving the File's Uri through the method Uri fileUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);. This works fine.
Then, I try to get the File whose Uri is the one I have. I do that this way:
File file = new File(fileUri.getPath());
But, afterwards, when I try to open it and read it, I get the java.io.FileNotFoundException ENOENT (No such file or directory). Furthermore, when I execute the file.exists() method, it returns false. So I don't know where the problem is.
Here is the code:
Uri fileUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
File file = new File(fileUri.getPath());
FileInputStream imageInFile = new FileInputStream(file);
What am I doing wrong?
EDIT:
I already have the <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> tag in my manifest.
I must also add that the uri of the file which I retrieve is something like: "/0/1/content:/media/external/images/media/9412/ACTUAL/1989334571". As you can see, the file doesn't have any extension at all, so that might be the problem. Nevertheless, I don't know how to solve it.
EDIT 2:
It seems as it is a problem that started since KitKat...

Related

How do I get the actual path of the video sent to my app from Gallery via the ContentProvider URI?

I have an app in which I'd like to view a video file that I chose to share from the Gallery to be edited. For that I know I have to use the intent-filter tag in the manifest of the Activity.
So here I was, selecting a video from the Gallery app to be 'shared' into this app. When the Activity opens, I used Uri videoUri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM); to retrieve the URI of the video. The URI looks like this:
content://com.google.android.apps.photos.contentprovider/-1/2/file%3A%2F%2F%2Fdata%2Fdata%2Fcom.google.android.apps.photos%2Fcache%2Fshare-cache%2Fmedia.tmp%3Ffilename%3Dimage.jpg/ORIGINAL/NONE/1804018524
I can play it just fine in MediaPlayer, but the problem comes when I have to use a library that requires a File [namely, MP4Parser], and that means a file path - this URI doesn't work.
I've parsed the file%3A%2F%2F%2Fdata%2Fdata%2Fcom.google.android.apps.photos%2Fcache%2Fshare-cache%2Fmedia.tmp%3Ffilename%3Dimage.jpg part, and it gives me:
file:///data/data/com.google.android.apps.photos/cache/share-cache/media.tmp?filename=image.jpg
The problem with this is that opening it results in an ENOENT. new File("/data/data/com.google.android.apps.photos/cache/share-cache/media.tmp").exists() returns false.
I've also queried the URI itself in the cursor via getContentResolver().query(uri, null, null, null, null) and logged all the values inside. All I got was:
_id:0
_display_name:image.jpg
_size:2183131
mime_type:video/mpeg
_data:null
orientation:0
datetaken:0
latitude:null
longitude:null
special_type_id:null
My question: Is there a way to inquire the actual path [either in file:// form or in content://media/external/videos/...] of the video shared by the Gallery app if that URI is what it sends out?
Turns out all I needed to do is to open an InputStream from said URI via the ContentResolver, write it into a FileOutputStream directed towards a temporary file (right now I have the temporary file inside my app's FilesDir), then use that as the data source instead.

How to pick file from external storage using file picker in Android

I am having a problem with selecting image file from external storage using file picker in Android. This question is the consequence of this question - No such file or diectory error in image file upload using Retrofit in Android. What my problem is opening and reading file from external storage on activity result. I want to convert result URI into File.
I read a pdf file from download folder on activity result
Uri bookUri = data.getData();
if(bookUri!=null)
{
String filePath = bookUri.toString();//bookUri.toString()
String mime = app.getMimeType(filePath);
if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
{
bookFile = new File(bookUri.getPath());
ivBookFile.setImageResource(R.drawable.book_selected);
}
else{
Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
}
}
As you can see I used new File(bookUri.getPath()); to convert into File. The above code works well. It is working. The problem is now I am trying to open an image file in DCIM/Camera folder on activity result.
This is the code I used
Uri selectedImageUri = data.getData();
if(selectedImageUri!=null)
{
try{
bmpCoverImage = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
imageFile = new File(selectedImageUri.getPath());
if(bmpCoverImage!=null)
{
ivCoverImage.setImageBitmap(bmpCoverImage);
}
}
catch (IOException e)
{
Toast.makeText(getBaseContext(),"An error occurred with the file selected",Toast.LENGTH_SHORT).show();
}
}
As you can see I used new File(selectedImageUri.getPath()); like I did in reading pdf file. This time the code is not working. When I do operation with the file like in previous question, it gives me error.
I used this way also
imageFile = new File(Environment.getExternalStorageDirectory(),selectedImageUri.getPath());
I got the same error. How can I open the image file correctly from external storage? How can I convert the chosen file URI from external storage into File?
I am having a problem with selecting image file from external storage using file picker in Android
If you are referring to the code that you are using in this question, you are not "using file picker". You are using ACTION_GET_CONTENT, which has never been a "file picker", nor will it ever be a "file picker".
I want to convert result URI into File.
Usually, that is not necessary. But, if that is what you want to do:
use ContentResolver and openInputStream() to get an InputStream on the content represented by the Uri
create a FileOutputStream on your desired file
use Java I/O to copy the bytes from the InputStream into the FileOutputStream
The above code works well. It is working.
It works for the small number of devices that you tested, for the specific activities that the user chose to handle the ACTION_GET_CONTENT request. It will not work on most Android devices, and it will not work in most circumstances. The only time that code will work is if the Uri has a file scheme. Most of the time, it will not. Instead, it will have a content scheme, representing content supplied by a ContentProvider.
Please how can I open the image file correctly from external storage?
If you wish to continue using ACTION_GET_CONTENT, please understand that this has nothing to do with external storage specifically. You are not getting a file, on external storage or elsewhere. You are getting a Uri. This is akin to a URL, such as the URL for this Web page. Just as a URL does not necessarily point to a file on your hard drive, a Uri does not necessarily point to a file on the filesystem. Use a ContentResolver and DocumentFile to work with the Uri and the content that it identifies.
If you want to always get files on external storage (and nowhere else), then use an actual file picker library.

can not load my image into a bitmap class in android

hi i have a problem with a bitmap and a picture located here:
file:///mnt/sdcard/Android/data/com.dev.app/files/Pictures/20120924-092226.jpg
so i have a string with this url (the the file exists!)
now i need to get a bitmap, so i do:
String str = "file:///mnt/sdcard/Android/data/com.dev.app/files/Pictures/20120924-092226.jpg";
Bitmap b = BitmapFactory.decodeFile(str);
but b is always null. and i dont know why.
EDIT: i create the file before with a code like this:
String filename = DateFormat.format("yyyyMMdd-hhmmss",Calendar.getInstance().getTime()) + ".jpg";
Uri imageUri = helper.createImageDestinationUri(null, filename);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, requestCode);
There are two possibilities
The file is of incorrect format, i.e although the extension is .jpg its not a jpeg file.
The file cannot be loaded.
You may have a closer look at the adb logs to see what is going on ... if it does not helps , try the following.
Add the file in your drawable folder, and use it in some Test screen. If the file gets displayed then the file format is correct , so android is not able to load the file. Check your permissions, and actually try and read the file first using FileInputStream or somthing else.
If the file is still not displayed then you can be sure that the format is wrong. In that case just try using a different image file.
Hope it helps...

Android open file

I was trying to open a file for reading.
When using: Scanner input = new Scanner(filename); the file could not be found
but when I used:
InputStream in = openFileInput(filename);
Scanner input = new Scanner(in);
It worked. Why was the first line of code wrong?
Files are stored on the device in a specific, application-dependent location, which is what I suppose openFileInput adds at the beginning of the file name. The final result (location + file name) is constructed as follows:
/data/data/<application-package>/files/<file-name>
Note also that the documentation states that the openFileInput parameter cannot contain path separators.
To avoid hard-coding the location path, which could in principle even be different from device to device, you can obtain a File object pointing to the storage directory by calling getFilesDir, and use it to read whatever file you would like to. For example:
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Note that constructing a Scanner by passing a String as a parameter would result in the scanner working on the content of the string, i.e. interpreting it as the actual content to scan instead of as the name of a file to open.
This drove me crazy couple of minutes ago. I forgot to add this line to manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I would expect a permission denied message. But just got a file not found...
In your case: openFileInput opens a file in your private app data directory (/data/data/your.package/filename). This never fails. But the scanner tries to open it on the root path. So when you want to read a file from SD card than you would use Environement.getExternalStorageDirectory().getAbsolutePath() + "/" + filename.
Scanner sc = new Scanner(new File(filename));

Android: Content type error using ACTION_VIEW with a local file

I'm trying to post a notification that lets the user open a locally stored file. My code looks like this:
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(filename));
notificationIntent.setData(uri);
Where "filename" is the full path to a locally stored file, usually in the /mnt/sdcard/download directory. The files I want to display are of various types: images, PDF documents, HTML, etc.
This works, but sometimes Android tries to open the file as the wrong type. For example, a jpeg file will open in a web browser view and instead of seeing the image, I see the binary data from the file displayed as text. Other times it works file. For example, some PDF files correctly open in a PDF viewer and some do not.
I'm not sure why this is. The documentation says I should not have to pass an explicit content type. If I do set the content type explicitly, things seem to work fine. The problem is, I don't always know what the content type should be (the file is downloaded from an external source and can be anything, and no, the MIME type is not in the HTTP headers, I checked for that).
What can I do here? Is there some function I can call with a filename to have Android return me the best content type for that file? Moreover, why is this not happening automatically when the Intent is processed?
Thanks.
You've most likely figured this out; I'm posting in case someone else is stuck on this. I do the following to get the mime-type of the file:
//Get the file path
Uri path = Uri.fromFile(file);
MimeTypeMap type_map = MimeTypeMap.getSingleton();
//Get the extension from the path
String extension = MimeTypeMap.getFileExtensionFromUrl(path.toString());
extension = extension.toLowerCase();
if (extension.contains(".")) {
extension = extension.substring(extension.lastIndexOf("."));
}
String mime_type = type_map.getMimeTypeFromExtension(extension);

Categories

Resources