Load image from gallery doesn't works twice - android

I select an image from the gallery. Now I load it in a temp-file and can show it in a ImageView. Everything works fine.
Uri uri = data.getData();
File file = new File(uri+"");
String fileName = file.getName();
String filePath = file.getParent();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
//here come's the code to save the temp-file and so on
In the fileName and filePath I save the name and path for later use. Because if the user want to save the image I want to make a copy of them.
URI shown in the debugger: content:/media/external/images/media/12345
filePath: content:/media/external/images/media
fileName: 12345
If I want to save the image I use the fileName and filePath to build the URI and want to do the same like above. But it doesn't works. I get a FileNotFoundException "no content provider" from the MediaStore. Hmm - before I deleted the App for a fresh testing there comes "No such file or directory" and I thought I eliminate the "no content provider" Exception with the READ_EXTERNAL_STORAGE permission.
Uri uri = Uri.parse(filePath +"/"+ fileName);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
Here I see also the correct URI in the debugger.
What is wrong?
I've set the permissions READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE in the AndroidManifest.

In the fileName and filePath I save the name and path for later use
A Uri is not a file, and yours most certainly is not a file.
What is wrong?
Your Uri has a content scheme. This is being served by a ContentProvider. You do not indicate where this Uri comes from, but I am going to guess that it is from ACTION_GET_DOCUMENT or something similar. In that case, like a Web URL that requires a working session, your access to the content identified by that Uri is short.
If you want to have longer-term access to the content, download it into your app, just as you would download content from a Web URL.

Related

Android get the actual filepath from gallery or google photos

I am trying to get the actual path of an image so that I can upload or send to server as multipart/form-data. So, Once I get the Uri, I have below code
Uri selectedImageUri = data.getData();
File file = new File(selectedImageUri.getPath());//create path from uri
final String[] split = file.getPath().split(":");//split the path.
String path = split[1];//assign it to a string(your choice).
uri value = content://com.android.providers.media.documents/document/image%3A32
path value = 32
I don't get it why path is a number, even I tried using getcontentResolver() and with that too I am getting path =32. I am using API 29 so I can't use MediaStore.Images.Media.DATA so, I have to use MediaStore.Images.Media._ID. It would be good if someone can also tell how to upload image as form-data too once i have path.

Cant save image to gallery

I am trying to save bitmap as an image to the phone storage with MediaStore like this:
MediaStore.Images.Media.insertImage(contentResolver, bitmap, "title" , "description")
The image was not saved inside the device storage, I have checked on both emulator and physical devices.
What I did so far:
Checked that the bitmap that I am passing is my wanted bitmap:
For this, I have checked its value with the help of the debugger like this:
1) Put a breakpoint on the line that supposed to save the image and check what bitmap I am passing, the bitmap was the same bitmap that I wanted to save:
2) This is how the bitmap looks like:
Made sure that the permission for writing files to the external storage (the line below) was granted from the user
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Made sure that the image was not saved at the end of the gallery or in any other place inside the device storage
I know that I can probably save the image without using MediaStore as mentioned in this thread but I want to know what I am doing wrong here and why I can't save the bitmap as an image inside the device storage.
I tried this but not worked for me too. So I used Android Download Manager, which is simple and easy ;-)
Here is the code
/*
This method can be used to download an image from the internet using a url in Android. This use Android Download Manager to
download the file and added it to the Gallery. Downloaded image will be saved to "Pictures"
Folder in your internal storage
*/
private void downloadImageNew(String filename, String downloadUrlOfImage){
try{
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(downloadUrlOfImage);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(filename)
.setMimeType("image/jpeg") // Your file type. You can use this code to download other file types also.
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,File.separator + filename + ".jpg");
dm.enqueue(request);
Toast.makeText(this, "Image download started.", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(this, "Image download failed.", Toast.LENGTH_SHORT).show();
}
}
For some reason even after WRITE_EXTERNAL_STORAGE was granted, after looking a bit on the logs I have noticed that I am getting this error:
Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=11218, uid=10079 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()
It looked weird to me because I have checked that this permission got granted before saving the image to the gallery.
What solved it for me was to delete the app and reinstall it again

ExifInterface_JNI: Raw image not detected error

When trying to get the ExifInterface I keep seeing a Raw image not detected error message.
ExifInterface exifInterface = new ExifInterface(filepath);
int rotation=exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_UNDEFINED);
Does anyone know what could be causing this?
I am getting it from a Uri but I know the filepath exists
Those statements are mutually contradictory. A Uri is not a file. If the scheme of the Uri is file, then and only then can you get a filesystem path to the file, by means of getPath(). If the scheme is anything else, such as content, then you cannot get a filesystem path, because there is no requirement that there be a file. For example, a Uri of http://stackoverflow.com/questions/42930509/exifinterface-jni-raw-image-not-detected-error does not mean that the Android device has a file at /questions/42930509/exifinterface-jni-raw-image-not-detected-error.
The ExifInterface from com.android.support:exifinterface (e.g., where the current latest version is 25.3.0) has a constructor that takes an InputStream. Create a ContentResolver (via getContentResolver() on a Context, such as your Activity). Call openInputStream() on that ContentResolver, supplying the Uri (works for both file and content schemes). Pass that InputStream to the library's ExifInterface constructor. This simultaneously ensures that you do not cause security problems for your users and avoids having to worry about getting a filesystem path for the content that you wish to examine.
Long story short, apply the below example to your code:
Uri uri = Uri.fromFile(f);
// where f of type File
in = context.getApplicationContext().getContentResolver().openInputStream(uri);
// context should refer to your context app
ExifInterface exifInterface = new ExifInterface(in);
// you'll need "exifInterface"
And don't forget to close your input stream
in.close();

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.

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

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...

Categories

Resources