In my application users select picture from gallery and upload. On many devices my code works perfect but on new devices (etc: samsung S5, LG G2, Samsung S4) application crashes
This code goes in your onActivityResult:
AsyncTask imageLoadAsyncTask = new AsyncTask() {
@Override
protected Bitmap doInBackground(Uri... uris) {
return getBitmapFromUri(uris[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
//crop, resize, play, do whatever with the bitmap
}
};
imageLoadAsyncTask.execute(data.getData());
This is getting called from AsyncTask because sometimes the images/files might not be stored locally like images backed up on Google+ or Google Drive. As recommended in this Devbyte video, always call it on the background thread.
private Bitmap getBitmapFromUri(Uri uri){
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return bitmap;
} catch (IOException e) {
Log.e(tag, "Failed to load image.", e);
e.printStackTrace();
return null;
} finally{
try {
if (parcelFileDescriptor != null) {
parcelFileDescriptor.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.e(tag, "Error closing ParcelFile Descriptor");
}
}
}
This is from the sample code for Storage Client Sample and I've tested it on Kitkat and Lollipop.
Will test on older versions and update. If anyone tests this on older version, let me know.
Update: Tested on JellyBean and it works.