Android file.canRead() = false when choosing image but not when TAKING photo - android

I have 2 buttons on an "upload image" page for users to upload an image to a web service. One is for selecting an image that is on your device, the other for taking a photo with your camera.
thisFragment.findViewById(R.id.btnChooseImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Assert.assertNotNull("file uri not null before firing intent", mFileUri);
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//this is the file that the camera app will write to
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
thisFragment.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Assert.assertNotNull("file uri not null before firing intent", mFileUri);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//this is the file that the camera app will write to
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
btnTakePhoto works fine when it loads an ImageView with the result when I TAKE a photo, but when I CHOOSE a photo using the other button the imageView is blank...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null) {
if(data.getData() != null) {
Log.v(LOG_TAG, "intent data: " + data.getData().toString());
}
if(data.getAction() != null) {
Log.v(LOG_TAG, "intent action: " + data.getAction().toString());
}
if(data.getExtras() != null) {
Log.v(LOG_TAG, "intent extras: " + data.getExtras().toString());
}
}
Assert.assertNotNull("file uri in onActivityResult", mFileUri);
Log.v(LOG_TAG, "stored file name is " + mFileUri.toString());
File file = getFileFromUri();
if(file != null) {
Bitmap bm = decodeSampledBitmapFromFile(file, 500, 500);
imgMain.setImageBitmap(bm);
}else{
imgMain.setImageBitmap(null);
}
} else {
parentActivity.finish();
}
}
private File getFileFromUri() {
if(mFileUri != null) {
try {
URI uri;
if(mFileUri.toString().startsWith("file://")){
//normal path
uri = URI.create(mFileUri.toString());
} else {
//support path
uri = URI.create("file://" + mFileUri.toString());
}
File file = new File(uri);
if (file != null) {
//if (file.canRead()) {
return file;
//}
}
} catch (Exception e) {
return null;
}
}
return null;
}
I noticed that when I hit this line of code:
if (file.canRead()) {
return file;
}
file.canRead() is TRUE when I take a picture, but FALSE when I CHOOSE a picture. When I step through and look at the value of the "uri" variable, here they are:
file:///storage/emulated/0/Pictures/IMG_20150916_141518.jpg - this works
file:///storage/emulated/0/Pictures/IMG_20150916_141854.jpg - this doesn't work
any idea what's going on here?
UPDATE: tried using the InputStream approach from ContentResolver, but the bitmap still can't be displayed:
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = parentActivity.getContentResolver().openInputStream(selectedImage);
}catch (FileNotFoundException e){
Log.v(LOG_TAG, "cant load file " + mFileUri.toString());
}
Bitmap bm = BitmapFactory.decodeStream(imageStream);
imgMain.setImageBitmap(bm);

Related

For a camera activity, result code is -1 in onActivityResult(). How to proceed debugging?

None of the submissions here deal with negative result code. I know it means that the task failed, but I have no idea how or why it failed. The app opens the camera and I'm able to take a picture.
btnN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage(v);
}
});
The function definitions are as given below.
public void captureImage(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null) {
Uri imageUri = FileProvider.getUriForFile(this, "com.example.testingproject.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, 1);
}
System.out.println("imageFile length:" + imageFile.length());
}
}
In the above function, I've even tried sending request code as 2. Same functionality, I'm able to click a picture, but same issue.
public File getImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmsss").format(new Date());
String imageName = "jpg_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageName, ".jpg", storageDir);
currentImagePath = imageFile.getAbsolutePath();
System.out.println("currImPath: " + currentImagePath);
return imageFile;
}
The much needed onActivityResult() code is below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
System.out.println("reqCode: "+requestCode+" resCode: "+resultCode);
switch (requestCode) {
case 0: {
if (resultCode == RESULT_OK) {
File file = new File(currentImagePath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
//...Do your stuffs
Toast.makeText(MainActivity.this, "Bitmap NOT null", Toast.LENGTH_SHORT).show();
imgView.setImageBitmap(bitmap);
}
else
{
Toast.makeText(MainActivity.this,"BitmapNull",Toast.LENGTH_SHORT).show();
}
}
break;
}
default: Toast.makeText(MainActivity.this,"result code not okay",Toast.LENGTH_SHORT).show(); break;
}
} catch (Exception error) {
error.printStackTrace();
}
}
The sysout in log is below
2020-05-01 13:52:24.644 10014-10014/com.example.testingproject I/System.out: reqCode: 1 resCode: -1
-1 is equal to RESULT_OK. It means the task completed successfully
When you look into the code. -1 is actully status code for RESULT_OK
public static final int RESULT_OK = -1;
Now you've set requestCode as 1 in this line
startActivityForResult(cameraIntent, 1);
So in your OnActivityResult which shows
reqCode: 1 resCode: -1
is Correct.

Androind ImageView in Fragment

I am trying to put an image on my fragment, but the image is not showing up. I am certain that it was working just yesterday but now it is not. Any help is appreciated.
This code is in my Fragment:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mUser = (User) getArguments().getSerializable(ARGS_USER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_picture_picker, container, false);
mImageView = v.findViewById(R.id.imageView);
mSelectImageButton = v.findViewById(R.id.select_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMG_REQUEST);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == IMG_REQUEST && resultCode == Activity.RESULT_OK && data != null){
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), path);
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
mUser.setProfilePicture(bitmap);
}catch(IOException e){
e.printStackTrace();
}
}
}
Actually you are not using the Volley. Please change the heading of your question. You are accessing the Gallery and showing the image inside the imageView. Use the below code for accessing the image from camera as well as gallery.
if (action.equals("CAMERA")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, ACTION_REQUEST_CAMERA);
} else {
openCamera();
}
} else if (action.equals("GALLERY")) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ACTION_REQUEST_GALLERY);
} else {
openGallery();
}
}
private void openCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
}
private void openGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
Intent chooser = Intent.createChooser(galleryIntent, "Choose a Picture");
getActivity().startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
System.out.println("resultCode: "+resultCode+"\n"+"requestCode: "+requestCode);
ImageOperations operations = new ImageOperations();
if (resultCode == RESULT_OK) {
if (requestCode == ACTION_REQUEST_GALLERY) {
System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
renderProfileImage(selectedImageUri,operations);
} else if (requestCode == ACTION_REQUEST_CAMERA) {
System.out.println("select file from camera ");
Bitmap photo = (Bitmap) data.getExtras().get("data");
String name = "profile_pic.png";
operations.saveImageToInternalStorage(photo,getActivity(),name);
profile_image.setImageBitmap(photo);
}
}
}
private void renderProfileImage(Uri selectedImageUri,ImageOperations operations) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
String name = "profile_pic.png";
operations.saveImageToInternalStorage(bitmap,getActivity(),name);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
private class ImageOperations {
public boolean saveImageToInternalStorage(Bitmap image, Context context, String name) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = context.openFileOutput("profile_pic.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
public Bitmap getThumbnail(Context context,String filename) {
String fullPath = Environment.getDataDirectory().getAbsolutePath();
Bitmap thumbnail = null;
// Look for the file on the external storage
try {
if (isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("Image",e.getMessage());
}
// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail()", ex.getMessage());
}
}
return thumbnail;
}
public boolean isSdReadable() {
boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}
return mExternalStorageAvailable;
}
}
action is like what you want to do. ACTION_REQUEST_GALLERY and ACTION_REQUEST_CAMERA use some integer constants like 100 and 101. profileImage is your ImageView.

Crop intent issue with Android M

This is my existing code for the crop intent. This works fine on all devices
private void choosePhotoFromCamera() {
System.out.println("choosePhotoFromCamera");
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (getExternalFilesDir(null) == null) {
Log.e(TAG, "No SDcard");
Log.e(TAG,
"Maybe this will work : "
+ Environment.getExternalStorageDirectory());
Toast.makeText(ChooseFromCamera.this, "The app needs SDcard inserted",
Toast.LENGTH_LONG).show();
return;
}
File imagFile = null;
try {
imagFile = File.createTempFile("" + System.currentTimeMillis(),
".jpg", getExternalFilesDir(null));
c= imagFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
uriForTempCapturePhoto = Uri.fromFile(imagFile);
String uristring= getPath(this, uriForTempCapturePhoto);
uriForTempCapturePhoto= Uri.parse(uristring);*/
i.putExtra(MediaStore.EXTRA_OUTPUT, uriForTempCapturePhoto);
startActivityForResult(i, TAKE_PHOTO_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
System.out.println("onActivityResult3333333333333333333333");
if (requestCode == TAKE_PHOTO_REQUEST_CODE
|| requestCode == SELECT_PHOTO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Uri uri = null;
if (requestCode == SELECT_PHOTO_REQUEST_CODE) {
uri = intent.getData();
} else if (requestCode == TAKE_PHOTO_REQUEST_CODE) {
uri = uriForTempCapturePhoto;
}
if (uri != null) {
try {
u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), c, null, null));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
}
final Intent intent1 = new Intent(
"com.android.camera.action.CROP");
System.out.println(" uri of the image "+uriForTempCapturePhoto);
intent1.setDataAndType(u, "image/*");
intent1.putExtra("" +"", "true");
intent1.putExtra("aspectX", 1);
intent1.putExtra("aspectY", 1);
intent1.putExtra("outputX", 100);
intent1.putExtra("outputY", 100);
intent1.putExtra("return-data", true);
startActivityForResult(intent1, CUT_PHOTO_REQUEST_CODE);
}
}else{
this.finish();
}
} else if (requestCode == CUT_PHOTO_REQUEST_CODE
|| requestCode == TAKE_GALLERY_REQUEST_CODE) {
if (resultCode == RESULT_OK && intent != null) {
System.out.println("4444444444444444444444444444444");
Bitmap bm = intent.getParcelableExtra("data");
if(bm != null){
System.out.println("Test : " + bm.toString());
}
else
System.out.println("Null Value");
Bitmap bmpCircular = createCircularBitmap(bm);
System.out.println("bmpCircular1111111111111111111"+bmpCircular);
/*if (bmpCircular == null) {
return;
}
String name = null;
String path = Utils.saveBitmap(
ChooseFromCamera.this.getApplicationContext(), name,
bmpCircular);
if (ChooseFromCamera.this == null) {
Log.e(TAG, "called this at wrong time.");
return;
}
if (path != null) {
// sucessfully
System.out.println("choosePhotoFromGallery1111111111111111111"+path);
setContentView(R.layout.main);
ivCamera = (ImageView) findViewById(R.id.iv_camera);
ivAccount = (RoundCornerImageView) findViewById(R.id.iv_account_indicator);
ivAccount.setImageBitmap(bmpCircular);
ivCamera.setVisibility(View.INVISIBLE);
}*/
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmpCircular.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
//String encoded = "abcdef";
System.out.println("encoded value"+encoded);
ChooseCamera.callKonyFunction(encoded);
this.finish();
}else{
this.finish();
}
}
}
Now when I test it in android M, I am getting the following exception.
java.lang.IllegalArgumentException: mediaStoreUri must be a MediaStore
Uri
To fix this issue insert image with mediastore and try to use the uri as below but this code also fails only in android M. Please help to fix.
if (uri != null) {
try {
u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), c, null, null));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{}
intent1.setDataAndType(u, "image/*");
Now i get only issue with Android M devices . The crop intent returns null in this case

Setting ImageView after Crop not working

I've created a basic activity with an imageView and two buttons. 1 Button opens the gallery, the other opens the camera. Both of which pass the result into a image cropping library. The cropped image is saved and shown in the imageView.
The first I do this with either button, everything works smoothly. However on the second attempt the imageView does not get replaced but the image that has been saved has changed.
So basically the imageView doesn't change to the new image if it already has the first result.
Here's Code:
public void takeDisplayPicture(View view) {
final String TAKE_DISPLAY_PICTURE = "Take Display Picture";
Log.d(TAKE_DISPLAY_PICTURE, "Clicked");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(TAKE_DISPLAY_PICTURE, "Error Occurred");
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
Log.d(TAKE_DISPLAY_PICTURE, photoFile.getAbsolutePath());
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} else {
Log.d(TAKE_DISPLAY_PICTURE, "No Camera");
Toast.makeText(getApplicationContext(),"No Camera Available",Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
final String ON_ACTIVITY_RESULT = "On Activity Result";
Log.d(ON_ACTIVITY_RESULT, "Triggered");
Log.d(ON_ACTIVITY_RESULT, "Request Code: "+Integer.toString(requestCode)+" Result Code: "+Integer.toString(resultCode));
Uri img = Uri.parse("file:///"+Config.APP_PATH+Config.APP_USER_PATH+"/"+Config.DISPLAY_PICTURE_NAME+".png");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Log.d(ON_ACTIVITY_RESULT, "Beginning Crop");
Log.d(ON_ACTIVITY_RESULT,img.toString());
beginCrop(img, img);
} else if (requestCode == Crop.REQUEST_CROP) {
Log.d(ON_ACTIVITY_RESULT, "Handling Crop");
handleCrop(resultCode, result);
} else if (requestCode == 2){
Log.d(ON_ACTIVITY_RESULT, "Gallery Image Returned");
File file = new File(img.getPath());
file.delete();
Uri src = result.getData();
Log.d(ON_ACTIVITY_RESULT, src.toString());
beginCrop(src, img);
}
}
private void beginCrop(Uri source, Uri output){
final String BEGIN_CROP = "Begin Crop";
Log.d(BEGIN_CROP, "Beginning");
new Crop(source).output(output).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
final String HANDLE_CROP = "Handle Crop";
if (resultCode == RESULT_OK) {
Log.d(HANDLE_CROP, "Set ImageView");
displayPicture.setImageURI(Crop.getOutput(result));
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Crop.getOutput(result));
} catch (Exception e ){
Log.d(HANDLE_CROP, "Error Occurred");
}
} else if (resultCode == Crop.RESULT_ERROR) {
Log.d(HANDLE_CROP, "Error Occurred");
}
}
String currentPhotoPath;
private File createImageFile() throws IOException {
final String CREATE_IMAGE_FILE = "Create Image File";
String fileName = "display_picture";
File dir = new File(Config.APP_PATH+Config.APP_USER_PATH);
dir.mkdirs();
File image = new File(dir,fileName+".png");
return image;
}
public void chooseFromGallery(View view) {
final String CHOOSE_FROM_GALLERY = "Choose From Gallery";
Log.d(CHOOSE_FROM_GALLERY, "Clicked");
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
If you read setImageURI:
if (mResource != 0 ||
(mUri != uri &&
(uri == null || mUri == null || !uri.equals(mUri)))) {
//Set URI...
}
Basically, setImageURI only works if the Uri of the image isn't equal to the Uri you want to currently set. Your button doesn't work second time because Crop.getOutput(result) returns the same Uri everytime you press the button, so setImageURI does nothing.
To solve this, you can add displayPicture.setImageURI(null); before displayPicture.setImageURI(Crop.getOutput(result));.

Capturing image from gallery & camera in android

First thing I know this is repeated question but I don't have problem in capturing image from gallery or camera. I created on dummy project to check my code here it's working fine
But when I used same code in my project & here it's not working even I didn't get any error
as soon as I start activity for result it get cancelled but still I can see images from gallery & I can capture image from camera.
When I checked logcat I found following warning don't know why it's coming & how I can fix this thing
W/NetworkConnectivityListener(2399): onReceived() called with CONNECTED and Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000000 (has extras) }
Edit:-- Added Code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
return true;
case R.id.gallery:
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gintent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
}
return false;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
Toast.makeText(this, "Picture was taken", Toast.LENGTH_SHORT).show();
Uri selectedImageUri = imageUri;
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
}
Thank You
Take a look at LinderdaumEngineActivity.java from my project Linderdaum Engine:
Capture image from camera:
public void CapturePhoto( String FileName )
{
try
{
File f = new File(FileName);
if ( f.exists() && f.canWrite() ) f.delete();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No camera: " + e );
}
catch ( Exception e )
{
Log.e( TAG, "Cannot make photo: " + e );
}
}
Open image from gallery:
public static void OpenImage()
{
try
{
Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
intent.setType( "image/*" );
startActivityForResult( intent, SELECT_PICTURE_CALLBACK );
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No gallery: " + e );
}
}
Also, do not forget to add permissions to your manifest:
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-permission android:name="android.permission.CAMERA" android:required="false"/>
Please check your AndroidManifest, make sure you have all the right permissions.
See official documentation with file provider for above android 7
getUriForFile(Context, String, File) which returns a content:// URI. For
more recent apps targeting Android 7.0 (API level 24) and higher, passing a
file:// URI across a package boundary causes a FileUriExposedException.
Therefore, we now present a more generic way of storing images using a
FileProvider.
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
Official doc

Categories

Resources