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);
}
}
}
Related
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()
}
This question already has answers here:
android:select image from gallery then crop that and show in an imageview
(3 answers)
android pick images from gallery
(19 answers)
Closed 4 years ago.
I am new to Android development and I tried my best to pick an image from gallery and saving within the app after cropping but I failed. Please help me to solve this issue. I tried to mix up different codes but nothing is working for me.
if (resultCode == RESULT_OK) {
//Uri photoUri = data.getData();
//if (photoUri != null) {
// photoPickerIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
CropImage.activity(android.net.Uri.parse(data.getDataString()))
.setAspectRatio(1,1)
.setFixAspectRatio(true)
.start(activity);
CropImage.ActivityResult result1 = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
iv.setImageURI(result1.getUri());
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result1.getError();
Log.d(TAG, "onActivityResult: " + error.getMessage());
}
//currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
//selectedImage.setImageBitmap(currentImage);
// }
First of All Add a dependency inside your project Gradle.built(app:odle) file
Like
dependencies {
implementaion 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
}
After that add following two permission inside manifiest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Create a Constant inside your class
private static final int REQUEST_FOR_GALLARY = 1;
you will need this .
After that Put the following Code inised your button on which u click to open gallery or whatever your are using .
Intent gallaryIntent = new Intent();
gallaryIntent.setAction(Intent.ACTION_GET_CONTENT);
gallaryIntent.setType("image/*");
startActivityForResult(gallaryIntent, REQUEST_FOR_GALLARY);
After that Override the medthod onActivityResult of your Activity class
Like
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_FOR_GALLARY && resultCode == RESULT_OK && data !=
null) {
Uri imageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
//Save image wherever you want to save it
}
}
}
Now Change your Code According to your Recuirement and Save image whereever you want to store .
I am developing a file uploading android application. My objective is to upload the user selected file from file manager to a remote server. But when a google drive file is selected , file uploading fails because of empty path . Can somebody help me ?
My code is :
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Choose File to Upload.."), PICK_FILE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) {
if (data == null) {
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(mActivity, selectedFileUri);
if (selectedFilePath != null && !selectedFilePath.equals("")) {
callUploadDocumentAPI();
} else {
Toast.makeText(mActivity, StringConstants.CANT_UPLOAD_TO_SERVER, Toast.LENGTH_SHORT).show();
}
}
}
But when a google drive file is selected , file uploading fails because of empty path .
FilePath.getPath(mActivity, selectedFileUri) cannot work. A Uri is not a file.
Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Either use that InputStream directly, or use it to make your own copy of the content in some file that you control, then use that copy.
This show the box with the applications to choose an image or take a picture with camera. If I select Camera this let me to take a picture but there is no return or save option. I updated my answer posting the activity result code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
Log.e("TAG", "Only called when a image from gallery is selected");
}
else
{
Log.e("TAG", "Data is null");
}
break;
}
}
private void ChooseImage()
{
// Create gallery intent
Intent _intentGallery = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
_intentGallery.setAction(Intent.ACTION_PICK);
_intentGallery.putExtra("return-data", true);
// startActivityForResult(_intentGallery, 1);
// Create camera intent
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Create chooser
Intent chooser = Intent.createChooser(galleryIntent, getString(R.string.choose_an_application));
// Create list of gallery intents
List<Intent> galleryIntents = new ArrayList<Intent>();
// Add intents to list
PackageManager pm = getApplicationContext().getPackageManager();
for (ResolveInfo ri: pm.queryIntentActivities(_intentGallery, PackageManager.MATCH_DEFAULT_ONLY))
{
Intent intent = pm.getLaunchIntentForPackage(ri.activityInfo.packageName);
intent.setAction(Intent.ACTION_PICK);
intent.putExtra("return-data", true);
galleryIntents.add(intent);
}
// Show dialog
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, galleryIntents.toArray(new Parcelable[] {}));
startActivityForResult(chooser, 1);
}
Manifest permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
You have to implement onActivityResult. Then you can get data.
#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);
}
}
In this case, REQUEST_IMAGE_CAPTURE is 1 as you defined it, so change it to 1.
Don't forget the manifest rule uses-feature.
See more: https://developer.android.com/training/camera/photobasics.html
I have an app where at an activity I am taking a photo (among other things) .
Now, when I press the button to take the photo it opens the camera.If i will press the back button or the cancel button (not taking photo) ,it crashes and gives
nullpointer
and
Failure delivering result ResultInfo
in this line:
Bitmap photo = (Bitmap) data.getExtras().get("data");
I use:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_REQUEST){
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
blobvalue = stream.toByteArray();
Bundle extras = new Bundle();
Intent k=new Intent(this,MainActivity.class);
extras.putParcelable("Bitmap", photo);
k.putExtras(extras);
}
if (requestCode == RESULT_CANCELED) {
}
}
and in my adapter:
ImageView myImage=(ImageView) convertView.findViewById(R.id.myimage);
final Bitmap image;
if(theItems.getImagemyItems() != null)
{
byte []temp = theItems.getImagemyItems();
image = BitmapFactory.decodeByteArray(temp, 0, temp.length);
myImage.setImageBitmap(image);
}
else
{
image = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
myImage.setImageBitmap(image);
}
As far as I remember , the above used to workd for this purpose.
I don't know what else to do.
You have just tested requestCode but haven't resultCode so I would suggest you to check resultCode whether user has captured image or cancel capturing.
Try:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST){
if (resultCode == Activity.RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
}
else if (resultCode == Activity.RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
You just have to place a check in your onActivityResult , the case RESULT_OK is when the user takes the picture successfully and the case RESULT_CANCELLED is when you press the hardware back button and want to return to your activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_REQUEST){
if(resultCode == RESULT_OK){
// your code comes here
}
if(resultCode == RESULT_CANCELED){
}
}
}