Problem retrieving picture from Camera intent in other than myself device (Oreo) - java

I am trying to get image from camera intent. Its working nice but only in my device (oreo / 8.1.0). I generate unsigned apk and tried to run in other device (pie and lolipop)but its not working.
I search stackoverflow and other sites, but people asked question about "camera intent problem in lolipop". My question is something different (I think).
I tried to check sdk version and apply different code. I.e. as per one answer from stackoverflow I used this code Picasso.get().load(file).into(imageView); instead of Picasso.get().load(photoURI).into(imageView); in LOLIPOP but its not working.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null; // Create the File where the photo should go
try {
photoFile = createImageFile();
tempPhoto = photoFile;
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.package.appname.fileprovider",
photoFile);
tempPhoto = photoFile;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
Code for createImageFile function:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Receiving result here
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
File file = new File(mCurrentPhotoPath);
Picasso.get().load(file).into(imageView);
// Bitmap bitmap = MediaStore.Images.Media
// .getBitmap(this.getContentResolver(), Uri.fromFile(file));
// if (bitmap != null) {
// imageView.setImageBitmap(bitmap);
// }
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
File file = new File(mCurrentPhotoPath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Exception error) {
error.printStackTrace();
}
}
Can anyone help me to give accurate result in all sdk versions? Please help me. Thanks in advance.

Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri uri = intent.getData(); // you need take uri of image
imageView.setImageURI(uri); // you don't need of picasso to load local images
// Picasso.get().load(file).into(imageView);
// Bitmap bitmap = MediaStore.Images.Media
// .getBitmap(this.getContentResolver(), Uri.fromFile(file));
// if (bitmap != null) {
// imageView.setImageBitmap(bitmap);
// }
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
File file = new File(mCurrentPhotoPath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Exception error) {
error.printStackTrace();
}
}

Related

I need a high quality image on my imageview, but I don't get any view in my imageview

This is my code for camera(i am using File Provider)
This is MainActivityMainActivity.java MainActivity.java
This is my display ActivityDisplayActivity.java
Plz help i tried so may codes and make projects again and again.
I am trying to get high quality image from the camera and display it on the imageview.
Here was an demo that can help with your project...
On Button Click...
//photoFile is global variable File photoFile = null;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 501);
}
} catch (Exception e) {
e.printStackTrace();
}
Put this method in your class
private File createImageFile() throws IOException {
long timeStamp = Calendar.getInstance().getTimeInMillis();
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
Get Result from camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 501:
if (photoFile != null) {
bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
if (bitmap != null) {
// you got bitmap here
}
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}

Android / Java WebView Fileupload fails in Android version 10 and 11

I have an android app in which i have a webview. This webview contains a File upload for uploading a picture which does work like a charm from Android 6 to 9. For version 10 it does still work if i use a picture from the gallery but if i try to use one directly through the camera it tells me that it doesn't have permission to the ExternalStorage. I have given it the access in the Settings since i haven't implemented the permission question. For Version 11 it's almost the same except i get no error at all. I have checked some things i think its because the Intent for "ACTION_IMAGE_CAPTURE" returns null for some reason. Did i miss something?
onShowFileChooser
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
Log.d("test", "Test1");
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(getApplicationContext(), "\"Unable to create Image File", Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
createImageFile() -> gives me error "Permission denied" even after giving it the Permissin in Settings
private File createImageFile() throws IOException {
try {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
} catch (Exception e) {
Log.d("test", e.getMessage());
return null;
}
}
onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getDataString() == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
Thanks in advance :D

Android App crashes after capturing image using camera intent

The application attempts to capture an image using the device's camera and upload it to FireBase. However, after an image is captured, the app crashes.
It shows the error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference
Functions in MainActivity:
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e("MainActivity", "Error creating file", e);
}
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance().getReference();
take_pic = (Button) findViewById(R.id.take_pic);
imageView = (ImageView) findViewById(R.id.pic_view);
progressDialog = new ProgressDialog(this);
take_pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
progressDialog.setMessage("Uploading...");
progressDialog.show();
StorageReference filepath;
Uri uri = data.getData();
filepath = storage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(photoURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
You are getting that errror because your intent.getData is null. It happened to me too, your onActivityResult when using the take picture intent always brings the data as null. As a workaround I made the photoURI a global variable in the activity and onActivityResult called it again. It would be something like this:
First you declare the variable
Uri myPhotoUri = null;
Then, you initiate it in your dispatchTakePictureIntent function:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e("MainActivity", "Error creating file", e);
}
if (photoFile != null) {
//you are adding initializing the uri
myPhotoUri = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
And on your onActivityResult, you use that uri to call to your firebase function. It will now have the information necessary to upload it:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
progressDialog.setMessage("Uploading...");
progressDialog.show();
StorageReference filepath;
//you delete the Uri uri = data.getData();
filepath = storage.child("Photos").child(uri.getLastPathSegment());
//here you call it
filepath.putFile(myPhotoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
First check that you have permission for using the camera, then
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);
Then onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQ && resultCode == Activity.RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
Bitmap.createScaledBitmap(bitmap, 150, 150, true);
}
}
then from bitmap to byte[]
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if(bitmap == null) return null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
You can now do whatever you want with the bitmap or byte[]

Android - image crop not loading image

I want to cut the photo I took from the gallery or the camera. But I can't see the photo in cropping activity. It just doesn't come. I take a photo from the camera and start the cutting activity. The screen just looks like this:
Camera and onActivityResult
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
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
Log.d("FotografHata",""+ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.maksu.aquarium.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri uri = Uri.parse(currentPhotoPath);
openCropActivity(uri, uri);
} else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
Uri uri = UCrop.getOutput(data);
}
}
openCropActivity
private void openCropActivity(Uri girenUri, Uri cikanUri) {
UCrop.of(girenUri, cikanUri)
.withAspectRatio(16, 9)
.start(this);
}
I was passing source and destination Uri by using Uri.parse(myFile) so it kept loading
What worked for me is that I used toUri(), like this
val sourceUri = myFile.toUri()

Using the camera intent to take a picture without an sdcard

I'm having trouble using the camera when there's no sdcard present.
When there is an sdcard, using the camera is trivial, e.g.
http://www.vogella.com/articles/AndroidCamera/article.html + a plethora of other examples.
However, I need to make my app available to devices which don't have SD cards, (e.g. the Sony Xperia series.) I've tried modifying the code such that I'm using the internal storage (I think):
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getDir("myDirec", Context.MODE_WORLD_WRITEABLE), "tmp_photo_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
file.createNewFile();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
However, upon result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentReturn) {
if (resultCode != RESULT_OK)
return;
String path = mImageCaptureUri.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(path);
...
bitmap is null.
Which leads me to believe that there's some permissions issue....maybe?
I've tried some of the other internal storage options, http://developer.android.com/guide/topics/data/data-storage.html#filesInternal e.g. getFilesDir() but the same result: null bitmap.
Has anyone had any success in using the camera without an sdcard?
Try this. It works..
private Uri imageUri;
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File dir = context.getDir("directory", Context.MODE_PRIVATE);
File photo = new File(dir, "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, OPEN_CAMERA);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case OPEN_CAMERA:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}

Categories

Resources