Unable to Decode Stream Image to Fragment - java

The Code Works perfectly but Im having problem with the Permission Denied but i already put READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permission on Android Manifest any idea. Already Tried this one Unable to decode stream: java.io.FileNotFoundException (Permission denied)
BitmapFactory﹕ Unable to decode stream - null
E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/storage/emulated/0/DCIM/Camera/IMG_20201001_125759.jpg (Permission
denied)
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity
//Open phone gallery
private void getImageFromGallery(){
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if the intent was to pick image, was successful and an image was picked
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null != data) {
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();
ImageView imageView = (ImageView) findViewById(R.id.the_grid_image_preview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}

If you're using Android version 6.0 or up, you need to ask for permissions in runtime:
https://developer.android.com/training/permissions/requesting
For this I use a nice wrapper called Dexter which simplifies it and is really easy to use.
You can then write this function in your Fragment:
private fun checkFilePermissions(onPermissionGranted: () -> Unit) {
Dexter.withActivity(activity)
.withPermissions(
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
)
.withListener(object : BaseMultiplePermissionsListener() {
override fun onPermissionsChecked(response: MultiplePermissionsReport) {
if (response.areAllPermissionsGranted()) {
onPermissionGranted()
}
}
})
.check()
}
And in when you call your method getImageFromGallery() just invoke it like this:
...
checkFilePermissions {
getImageFromGallery()
}

Related

FileNotFoundException when getting thumbnail from video ANDROID

I have a problem when I'm trying to get video thumbnail from phone gallery videos. I have a method which is getting bitmap of video thumbnail,but this method is not working perfectly. The minus of mine method is that,for some videos it's not working and I'm getting "FileNotFoundException",but for some videos this method is working fine.
private void pickVideosFromGallery() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_VIDEO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK){
return;
}
switch (requestCode)
{
case SELECTED_VIDEO:
Uri uri = data.getData();
String[] projection = {MediaStore.Video.VideoColumns.DATA};
Cursor cursor = getContext().getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bit = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
break;
}}
07-16 20:11:49.647 32387-32387/com.example.tstv.keepfavoritevideos E/folderFragment: Video Path: android.graphics.Bitmap#71d9de1
07-16 20:12:49.992 32387-32387/com.example.tstv.keepfavoritevideos E/MediaMetadataRetriever: setDataSource - FileNotFoundException
07-16 20:12:49.992 32387-32387/com.example.tstv.keepfavoritevideos E/folderFragment: Video Path: null
As you can see from that LOG, for some videos its working, and I am getting bitmap,but for some its not working. WHY?

"Permission denied" on file after taking photo in ACTION_IMAGE_CAPTURE intent

In my activity, I have the following code:
public void myMethod() {
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_" + System.currentTimeMillis() + ".jpg";
outputFileUri = Uri.fromFile(new File(root, fname));
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outputFileUri);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 232);
startActivityForResult(takePhotoIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 232) {
myMethod();
} else {
System.out.println("returned...");
ImageView imageView = (ImageView) findViewById(R.id.test_image_view);
imageView.setImageURI(outputFileUri);
}
}
My test device is a rooted nexus 6 on Android 6.0.1. When "myMethod" is called, it lets me take the photo, but upon returning to the activity I get the following error:
java.io.FileNotFoundException: /storage/emulated/0/MyDir/img_1466772411267.jpg: open failed: EACCES (Permission denied)
I have the valid permissions declared in my manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera"/>
This error happens on the end of the method (I guess because the prior takes some time to throw the error?) Anyway, from what I see, I appear to be doing things the way I should be. Does anything seem off?
Your code will work till Android 5.0 but not in marshmallow os.
As Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app even though you had given permission in manifest file.
So app need to ask permission from user at runtime and if user does not give that permission you will get permission denial error. So you have to manage code for that.
Refer following link for more details:
https://developer.android.com/training/permissions/requesting.html
Runtime Permissions for Android 6.0
private static final int REQUEST_RUNTIME_PERMISSION = 1;
void checkPremission() {
//select which permission you want
final String permission = Manifest.permission.CAMERA;
//final String permission = Manifest.permission.Storage;
// if in fragment use getActivity()
if (ContextCompat.checkSelfPermission(ActivityName.this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ActivityName.this, permission)) {
} else {
ActivityCompat.requestPermissions(ActivityName.this, new String[]{android.permission.CAMERA,android.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_RUNTIME_PERMISSION);
}
} else {
// you have permission go ahead
myMethod();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_RUNTIME_PERMISSION:
final int numOfRequest = grantResults.length;
final boolean isGranted = numOfRequest == 1
&& PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
if (isGranted) {
// you have permission go ahead
myMethod();
}else{
// you dont have permission show toast
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Android Program Crashing NullPoint Exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hey so I have been trying to fix this problem for a couple of hours and checked a lot of the other questions extensively in an attempt to remedy this problem.
So in my Main Activity I have two activities that both either grabs an image from the gallery or is a photo depending on the button
public void DoTakePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, TAKE_PICTURE);
}
}
public void DoShowSelectImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
So I know the problem likes on my onActivityResult where the data seems to be null I tried using the super so it gets back the lost activity or checking to see if data is
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE || requestCode == TAKE_PICTURE && null != data) {
if (resultCode == RESULT_OK && null != data) {
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]);
mImageFullPathAndName = cursor.getString(columnIndex);
cursor.close();
jobID = "";
File file = new File(mImageFullPathAndName);
Bitmap mCurrentSelectedBitmap = decodeFile(file);
if (mCurrentSelectedBitmap != null) {
ivSelectedImg.setImageBitmap(mCurrentSelectedBitmap);
int w = mCurrentSelectedBitmap.getWidth();
int h = mCurrentSelectedBitmap.getHeight();
int length = (w > h) ? w : h;
if (length > OPTIMIZED_LENGTH) {
float ratio = (float) w / h;
int newW, newH = 0;
if (ratio > 1.0) {
newW = OPTIMIZED_LENGTH;
newH = (int) (OPTIMIZED_LENGTH / ratio);
} else {
newH = OPTIMIZED_LENGTH;
newW = (int) (OPTIMIZED_LENGTH * ratio);
}
mCurrentSelectedBitmap = rescaleBitmap(mCurrentSelectedBitmap, newW, newH);
}
mImageFullPathAndName = SaveImage(mCurrentSelectedBitmap);
}
}
}
}
So my Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.zola.capchem/com.example.zola.capchem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
I have tried most of the things on this site but the app still ends up crashing. No clue what to do here.
Your code would crash if you try to take a picture from the camera.
The method for taking a photo via camera and obtaining a photo from the gallery/file system is quite different.
For doing both, you fire an intent with an ACTION and some extras. You launch an activity for a result with this intent. The result is returned to you in onActivityResult() via the intent passed to it.
However, the result stored in the returned intent is different for both cases.
1) Taking a photo through camera: The bitmap itself of the image taken is returned to you, as an extra in the intent bundle. You can access it as:
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
//use bitmap however you like...
2) Select a photo from gallery: You may or may not get a URI of the selected image (via data.getUri()). In case you get an URI, you can obtain your image through that URI. However, this uri may be null sometimes, in which case the android system has chosen to write the image on to the image URI that you had passed as an intent extra while launching the activity for result.
Hence, first, define a temporary URI and use it to launch the activity to select image from gallery:
private URI getTempFile()
{
if (isExternalStorageWritable())
{
File file = new File(Environment.getExternalStorageDirectory(), "temporary_file.jpg");
try
{
if(!file.exists())
{
file.createNewFile();
}
} catch (IOException e)
{
}
return Uri.fromFile(file);
} else
{
return null;
}
}
public void DoShowSelectImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
startActivityForResult(i, SELECT_PICTURE);
}
and inside your onActivityResult:
Uri selectedimage = data.getData();
if(selectedimage == null)
{
selectedimage = getTempFile();
}
You need to handle both these cases seperately in your onActivityResult:
if(result == RESULT_OK && data != null)
{
Bitmap mCurrentSelectedBitmap;
if(requestCode == SELECT_PICTURE)
{
Uri selectedimage = data.getData();
if(selectedimage == null)
{
selectedimage = getTempFile();
}
......
......
mCurrentSelectedBitmap = decodeFile(file);
}
else if(requestCode == TAKE_PICTURE)
{
Bundle extras = data.getExtras();
mCurrentSelectedBitmap = (Bitmap) extras.get("data");
}
.......
.......
//Do your thing
}
NOTE: you might need to add permission in your manifest to write to external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()'

I am Trying To upload image to server from gallery and camera.When i Choose image from gallery to upload to server its Work Perfactly.But when i Select camera captured Image for upload to server Its Crash And Showing the error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
At OnActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
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();
decodeFile(picturePath);
new ImageUploadTask().execute();
}else {
Toast.makeText(getApplicationContext(), "User Canceled",
Toast.LENGTH_LONG).show();
}
}
i got the error on this line in onActivityResult
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
The method i used for open camera on button click.
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Info.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
}
})
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Help Me solve this problem.I don't know How t get this error even after i used is already in my Previous PROJECT.
THANKS in Advance
I had same issue when working with Camera api and Intent of onActivityResult, finally I found out it depends on your android device version, in Android M (Marshmallow - 6.0–6.0.1 ) onActivityResult intent is like below :
requestCode : 230 resultCode : -1 intent :Intent{dat=file:///storage/emulated/0/Pictures/Rahnama/IMG_20160508_121332_1519065 564.jpg typ=image/jpeg } RESULT_OK : -1
and for android versions lower than Marshmallow:
requestCode : 230 resultCode : -1 intent : Intent { dat=content://media/external/images/media/309 (has extras) } RESULT_OK : -1
I think you must check android version onActivityResult and the for android versions Marshmallow to get direct file from path in the Uri and Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M){
final Uri data = intent.getData();
final File file = new File(data.getPath());
// now you can upload your image file
}else{
// in android version lower than M your method must work
}
I hope it can be useful for you.
if (null != account.getPhotoUrl()) {
// Write code here
}
I meet this problem either, after many test, I found its because I set the attribute named android:windowIsTranslucent=true, if I delete this attribute from style, it always work.

Image is not being picked of my gallery: Failure delivering resultInfo

I am trying to pick picture of my gallery I can access my Gallery but after clicking the image the app crashed.
I try to debug it and it crashed in the onActivityResult method at this line InputStream openInputStream = getContentResolver().openInputStream(photoLocation);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY) {
Uri photoLocation = data.getData();
try {
InputStream openInputStream = getContentResolver().openInputStream(photoLocation);
selectedImage = BitmapFactory.decodeStream(openInputStream);
imagePlantsearch.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image",Toast.LENGTH_LONG).show();
}
}
}
}
You forgot to write permission for reading files from device. Just add below line to your AndroidManifest.xml file.
Add Read Permission to Manifest File.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If you have read your error carefully. It was already suggested by it to add permission to Manifest file.
insert permission first in your manifest and then add following code..
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
add this code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}

Categories