Cannot use Poly Picker multiple image picker library in Android - android

I am developing an Android app. In my app, I want to let user to choose multiple when user clicks upload button. So I used this library. I can successfully pop up dialog and choose multiple files. But the problem is when I convert URI of selected images to bitmap in onActivityResult, it is giving me error.
This is how I pop up picker in activity:
private void getImages() {
Intent intent = new Intent(GalleryActivity.this, ImagePickerActivity.class);
nl.changer.polypicker.Config pickerConfig = new nl.changer.polypicker.Config(R.color.white,R.color.blue,10,R.color.green);
ImagePickerActivity.setConfig(pickerConfig);
startActivityForResult(intent, INTENT_REQUEST_GET_IMAGES);
}
This is how I am converting to bitmap on result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == INTENT_REQUEST_GET_IMAGES) {
Parcelable[] parcelableUris = data.getParcelableArrayExtra(ImagePickerActivity.EXTRA_IMAGE_URIS);
if (parcelableUris == null) {
return;
}
// Java doesn't allow array casting, this is a little hack
Uri[] uris = new Uri[parcelableUris.length];
System.arraycopy(parcelableUris, 0, uris, 0, parcelableUris.length);
if (uris != null) {
bitmaps = new ArrayList<Bitmap>();
for (Uri uri : uris) {
try{
if(uri!=null)
{
Bitmap bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmaps.add(bmp);
}
}
catch (IOException e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
if(bitmaps.size()>0)
{
confirmFileUpload();
}
}
}
}
}
As you can see above my code, it will reach to io exception block of try-catch statement.
This is the example of error toasted:
That kind of error throw whatever image I select. What is wrong with my code and how can I fix it?

Finally I found the solution. I problem was when I parse uri to string, the format is something like this:
/sdcard/download/filename.png
The uri string must be in this format:
file:///sdcard/download/filename.png
No Content Provider Found exception throws because my uri string does not have required prefix. So I convert the uri to string. Then added the prefix. Then I parse that string to URI back. Then it worked successfully.

Related

Can't use Storage Access Framework in my app

I created an app a few years ago which had it's own file explorer and does so many processes on selected files. recently I wanted to add ability to write to external storages like SD Cards and Hard drives connected through OTG.
The problem is I can't rewrite the whole project based on DocumentFile structure since it's a very big project and it would take forever for me to update. So I needed to somehow convert the old File methods in a few lines and be done with it. this is what I've added so far :
private void getPersistentPermission() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, reqcode_storage);
}
and :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == reqcode_storage) {
Uri uri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final int perm_flag = Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
grantUriPermission(getPackageName(), uri, perm_flag);
getContentResolver().takePersistableUriPermission(uri, perm_flag);
}
}
} else {
Log.d(tag, "something`s wrong !");
}
}
then I try to do something like this :
try {
DocumentFile dfile = DocumentFile.fromFile(file);
OutputStream os = getContentResolver().openOutputStream(dfile.getUri());
os.write(some_string.getBytes());
} catch (Exception e) {
Log.e(tag, e.toString());
} finally {
try {
os.close();
} catch (Exception ignored) {}
}
I get the "file" using implemented file explorer inside my app. it works for internal storage.
I read so many threads about SAF but somehow I can't get it to work. it always shows this error :
java.io.FileNotFoundException: Permission denied
Can anyone tell me what am I missing here ?
thanks in advance.

How to convert a content Uri into a File

I know there are a ton of questions about this exact topic, but after spending two days reading and trying them, none seamed to fix my problem.
This is my code:
I launch the ACTION_GET_CONTENT in my onCreate()
Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
selectIntent.setType("audio/*");
startActivityForResult(selectIntent, AUDIO_REQUEST_CODE);
retrieve the Uri in onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUDIO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if ((data != null) && (data.getData() != null)) {
audio = data.getData();
}
}
}
pass the Uri to another activity and retrieve it
Intent debugIntent = new Intent(this, Debug.class);
Bundle bundle = new Bundle();
bundle.putString("audio", audio.toString());
debugIntent.putExtras(bundle);
startActivity(debugIntent);
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
audio = Uri.parse((String) bundle.get("audio"));
The I have implemented this method based on another SO answer. To get the actual Path of the Uri
public static String getRealPathFromUri(Activity activity, Uri contentUri) {
String[] proj = { MediaStore.Audio.Media.DATA };
Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and in the Debug activity's onCreate() I try to generate the file:
File audioFile = new File(getRealPathFromUri(this, audio));
This is how the error looks like:
Caused by: java.lang.NullPointerException
at java.io.File.(File.java:262)
at com.dancam.lietome.Debug.onCreate(Debug.java:35)
When I run the app I get a NPE on this last line. The audio Uri, isn't NULL though so I don't understand from what it is caused.
I'd really appreciate if you helped me out.
This is the library I'm trying to work with.
Note: I know exactly what NPE is, but even debugging I couldn't figure out from what it is caused in this specific case.
pass the Uri to another activity and retrieve it
Your other activity does not necessarily have rights to work with the content identified by the Uri. Add FLAG_GRANT_READ_URI_PERMISSION to the Intent used to start that activity, and pass the Uri via the "data" facet of the Intent (setData()), not an extra.
To get the actual Path of the Uri
First, there is no requirement that the Uri that you get back be from the MediaStore.
Second, managedQuery() has been deprecated for six years.
Third, there is no requirement that the path that MediaStore has be one that you can use. For example, the audio file might be on removable storage, and while MediaStore can access it, you cannot.
How to convert a content Uri into a File
On a background thread:
Get a ContentResolver by calling getContentResolver() on a Context
Call openInputStream() on the ContentResolver, passing in the Uri that you obtained from ACTION_GET_CONTENT, to get an InputStream on the content identified by the Uri
Create a FileOutputStream on some File, where you want the content to be stored
Use Java I/O to copy the content from the InputStream to the FileOutputStream, closing both streams when you are done
I ran into same problem for Android Q, so I end up creating a new file and use input stream from content to fill that file
Here's How I do it in kotlin:
private var pdfFile: File? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
when (requestCode) {
REQUEST_CODE_DOC -> {
data.data?.let {
if (it.scheme.equals("content")) {
val pdfBytes =
(contentResolver?.openInputStream(it))?.readBytes()
pdfFile = File(
getExternalFilesDir(null),
"Lesson ${Calendar.getInstance().time}t.pdf"
)
if (pdfFile!!.exists())
pdfFile!!.delete()
try {
val fos = FileOutputStream(pdfFile!!.path)
fos.write(pdfBytes)
fos.close()
} catch (e: Exception) {
Timber.e("PDF File", "Exception in pdf callback", e)
}
} else {
pdfFile = it.toFile()
}
}
}
}
}
}
}
Daniele, you can get path of file directly from data like below in onActivityResult():
String gilePath = data.getData().getPath();

How to get the real file path in android [duplicate]

The reason why I am asking this is because the callback of the file chooser Intent returns an Uri.
Open file chooser via Intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), CHOOSE_IMAGE_REQUEST);
Callback:
#Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
if (data == null) {
// Error
return;
}
Uri fileUri = data.getData();
InputStream in = getContentResolver().openInputStream(fileUri);
// How to determine image orientation through Exif data here?
}
}
One way would be to write the InputStream to an actual File, but this seems like a bad workaround for me.
After the 25.1.0 support library was introduced, now is possible to read exif data from URI contents (content:// or file://) through an InputStream.
Example:
First add this line to your gradle file:
compile 'com.android.support:exifinterface:25.1.0'
Uri uri; // the URI you've received from the other app
InputStream in;
try {
in = getContentResolver().openInputStream(uri);
ExifInterface exifInterface = new ExifInterface(in);
// Now you can extract any Exif tag you want
// Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
// Handle any errors
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
For more information check: Introducing the ExifInterface Support Library, ExifInterface.

How does "putExtra" work?

I'm following along on this example:
http://developer.android.com/training/camera/photobasics.html
If you Ctrl-F for this putExtra(MediaStore.EXTRA_OUTPUT it'll take you to a segment of code I'm unsure of. Further up in the app, they override onActivityResult and try to pull the image from this intent out of the activity result to display in the app, but when I was doing this the Intent arg in onActivityResult was null. I tried changing my putExtra to take "data" instead of MediaStore.EXTRA_OUTPUT and suddenly it works perfectly.
Can anyone explain what this tutorial is trying to get me to do?
So basically, the code in question:
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
Intent data in onActivityResult is null, so it'd crash when i called getExtras. I changed dispatchTakePictureIntent to putExtra("data", Uri.fromFile(photoFile)); and it works.
I'm just confused if this is a blunder on Google's part and made a mistake in their tutorial, or if I did something wrong / don't understand? Only reason I thought to make this change is because it uses the string data when it calls extras.get("data"). So I don't even understand my solution :(
putExtra("NameOfExtra", object)
so they are getting an extra named "data" - the string is the NAME of the extra value that was previously put.

How to open file save dialog in android?

I have a web service which give me a byte[] array according to image id . I want to convert these byte[] to file and store a file on android where user want like save file dialog box with file same format exactly it has.
Since this is the top result in google when you search for that topic and it confused me a lot when I researched it, I thought I add an update to this question.
Since Android 19 there IS a built in save dialog. You dont event need any permission to do it (not even WRITE_EXTERNAL_STORAGE).
The way it works is pretty simple:
//send an ACTION_CREATE_DOCUMENT intent to the system. It will open a dialog where the user can choose a location and a filename
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("YOUR FILETYPE"); //not needed, but maybe usefull
intent.putExtra(Intent.EXTRA_TITLE, "YOUR FILENAME"); //not needed, but maybe usefull
startActivityForResult(intent, SOME_INTEGER);
...
//after the user has selected a location you get an uri where you can write your data to:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SOME_INTEGER && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
//just as an example, I am writing a String to the Uri I received from the user:
try {
OutputStream output = getContext().getContentResolver().openOutputStream(uri);
output.write(SOME_CONTENT.getBytes());
output.flush();
output.close();
}
catch(IOException e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
}
}
More here:
https://developer.android.com/guide/topics/providers/document-provider
The Android SDK does not provide its own file dialog, therefore you have to build your own.
You cant create a save file dialog but you can save files from ur application to android sd card with the help of below links
http://android-er.blogspot.com/2010/07/save-file-to-sd-card.html
http://www.blackmoonit.com/android/filebrowser/intents#intent.pick_file.new
First, you should create a dialog intent for saving the file, After selection by the user, you can write on that directory and specified the file without any read/write permissions. ( Since Android 19 )
Source:https://developer.android.com/training/data-storage/shared/documents-files#create-file
// Request code for creating a PDF document.
private final int SAVE_DOCUMENT_REQUEST_CODE = 0x445;
private File targetFile;
private void createFile() {
Uri reportFileUri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", targetFile);
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, targetFile.getName());
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, SAVE_DOCUMENT_REQUEST_CODE );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SAVE_DOCUMENT_REQUEST_CODE && resultCode == RESULT_OK){
Uri uri = data.getData();
saveFile(uri);
}
}
private void saveFile(Uri uri) {
try {
OutputStream output = getContentResolver().openOutputStream(uri);
FileInputStream fileInputStream = new FileInputStream(targetFile);
byte[] bytes = new byte[(int) targetFile.length()];
fileInputStream.read(bytes, 0, bytes.length);
output.write(bytes);
output.flush();
output.close();
Log.i(TAG, "done");
} catch (IOException e) {
Log.e(TAG, "onActivityResult: ", e);
}
}
#JodliDev already provided the accepted answer, however, startActivityForResult is now deprecated, so I want to provide my solution here using registerForActivityResult(ActivityResultContracts.CreateDocument())
First register a ActivityResultLauncher where you define what should happen with the result. We'll get the uri back that we can use for our OutpuStream. But make sure to initialize it at the beginning, otherwise you will get:
Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).
private var ics: String? = null
private val getFileUriForSavingICS = registerForActivityResult(ActivityResultContracts.CreateDocument()) { uri ->
if(ics.isNullOrEmpty())
return#registerForActivityResult
try {
val output: OutputStream? =
context?.contentResolver?.openOutputStream(uri)
output?.write(ics?.toByteArray())
output?.flush()
output?.close()
} catch (e: IOException) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
}
}
Then just call your ActivityResultLauncher with .launch(...) wherever it is needed.
getFileUriForSavingICS.launch("filename.txt")
And that's about it ;-)
You can also have a closer look at ActivityResultContracts.CreateDocument(). This method provides the document saving dialog, but there are other helpful functions inside (like for starting a camera intent). Check out:
https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts
for the possible ActivityResultContracts
Or https://developer.android.com/training/basics/intents/result for some more training material and also some information how a custom contract could be created!

Categories

Resources