Take picture from camera and pass URI to another activity - java

When I try to get the URI on the onActivityResult() method, I get a null pointer exception.
I need to take a picture from the device camera and then pass the URI to the next activity.
That's my actual code:
public void takePicFromCamera(View view){
if (Build.VERSION.SDK_INT >= 24) {
try {
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "IMG_FOLDER");
imageUri = Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator +
"profile_img.jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 2);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode != 0) {
Uri sel_img = data.getData();
Intent intent = new Intent(MainActivity.this, RateActivity.class);
intent.putExtra("uri", sel_img.toString());
startActivity(intent);
}
if(requestCode == 2 && resultCode != 0){
Intent intent = new Intent(MainActivity.this, RateActivity.class);
intent.putExtra("uri", imageUri.toString());
startActivity(intent);
}
}
The RateActivity after I take the image, doesn't start

Related

I want to select multiple images from gallery but after selecting images when I click on open its crash

I want to select multiple images from gallery but after selecting images when I click on open the app crashes.
My code:
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
Toast.makeText(this, "images pick"+imageUri, Toast.LENGTH_SHORT).show();
TextView txtview = findViewById(R.id.imguri);
txtview.setText(String.valueOf(imageUri));
Intent intent = new Intent(MainActivity.this,ConvertActivity.class);
intent.putExtra("ImageUri",imageUri.toString());
startActivity(intent);
// image_view.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
///pick gallery code
public void pickGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
your Intent
Intent chooserIntent = new Intent();
chooserIntent.setType("image/*");
chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
chooserIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(chooserIntent, "Select
Picture"), 100);
Activity Result
override fun onActivityResult(requestCode: Int, resultCode: Int, data:
Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100 && resultCode == RESULT_OK && data!=null) {
val clipdata = data.clipData
if(clipdata!=null){
for (i in 0 until data?.clipData!!.itemCount) {
val uri = data?.clipData?.getItemAt(i)?.uri
songlist.add(uri)}
}else{
val uri = data?.data
songlist.add(uri)
}
}

Capture photo intent resultCode

How can I detect wether the user take picture and selects it (with the confirm button on camera) or they just turn on a camera, take a picture and remove it (with the cancel button on camera)
When the user take picture I am loading that picture into an ImageView. If user hits confirm button then everything is OK but if user don't want that picture and decide to hit cancel button then the ImageView goes blank.
This is my camera intent :
void capturePhoto() {
// ImagePicker.pickImage(this, "Select your image:");
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 f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
Uri photoURI = Uri.fromFile(f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
pictureUri = null;
}
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
And onActivityResult, in both cases the resultCode is always 1. (note that RESULT_OK is -1) and I dont know why.
This is how I set image to ImageView using Glide:
Glide.with(this).load(mCurrentPhotoPath).centerCrop().into(imageView);
Any Suggestions?
Thanks!
you just need to pass if statement in onActivityresult
cause if you use directly that URI or whatever you use which has no any frame set cause user cancel it so just do as given
//if needed than
//public static final int RESULT_OK = -1;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
//do your stuff here
}
}
You can use below code
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (isCameraPermissionEnabled()) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
1);
}
}
}
public boolean isCameraPermissionEnabled() {
return !(Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED );
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
mBitmap = (Bitmap) extras.get("data");
imageView.setBackground(new BitmapDrawable(getResources(),mBitmap));
}
}
//For more information https://developer.android.com/training/camera/photobasics.html

Image displays when choosing from gallery but not when capturing from camera

On the press of a button, dispatchTakePictureIntent() lets the user choose between taking a picture or choosing one from the gallery four times. These four URIs are stored in an ArrayList and the four should be shown in their respective ImageViews. The problem I'm having is that when I "capture a picture", it doesn't show in the ImageView right away; but the pictures I chose from gallery do.
The picture I captured is properly saved and can be found in "choose from gallery" the next time I press the button. Can anybody see what I'm doing wrong?
takePictureIntent():
private void dispatchTakePictureIntent() {
for(int i = 0; i < 4; i++) {
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();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
if(id.equals(HAPPY_ID))
startActivityForResult(chooserIntent, REQUEST_HAPPY_PHOTO);
if(id.equals(SURPRISED_ID))
startActivityForResult(chooserIntent, REQUEST_SURPRISED_PHOTO);
if(id.equals(AFRAID_ID))
startActivityForResult(chooserIntent, REQUEST_AFRAID_PHOTO);
if(id.equals(UPSET_ID))
startActivityForResult(chooserIntent, REQUEST_UPSET_PHOTO);
if(id.equals(SAD_ID))
startActivityForResult(chooserIntent, REQUEST_SAD_PHOTO);
}
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_HAPPY_PHOTO || requestCode == REQUEST_SURPRISED_PHOTO || requestCode == REQUEST_AFRAID_PHOTO ||
requestCode == REQUEST_UPSET_PHOTO || requestCode == REQUEST_SAD_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
//Log.d("doing ids", "right before id");
//Log.d("doing ids", "id is " + id);
if(requestCode == REQUEST_HAPPY_PHOTO) {
//Log.d("doing ids", "in happy");
happyList.add(selectedImageUri);
}
if(requestCode == REQUEST_SURPRISED_PHOTO) {
//Log.d("doing ids", "in surprised");
surprisedList.add(selectedImageUri);
}
if(requestCode == REQUEST_AFRAID_PHOTO) {
//Log.d("doing ids", "in surprised");
afraidList.add(selectedImageUri);
}
if(requestCode == REQUEST_UPSET_PHOTO) {
//Log.d("doing ids", "in surprised");
upsetList.add(selectedImageUri);
}
if(requestCode == REQUEST_SAD_PHOTO) {
//Log.d("doing ids", "in surprised");
sadList.add(selectedImageUri);
}
}
}
}
Try this, this works for me
public Uri captureImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (chooserIntent.resolveActivity(getPackageManager()) != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Image File name");
Uri takenImageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, takenImageUri);
startActivityForResult(intentPicture, MyConstants.REQUEST_IMAGE_CAPTURE);
return takenImageUri;
}
return null;
}
public String getRealPathFromURI(Uri contentUri){
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e){
return contentUri.getPath();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
switch (requestCode){
case MyConstants.REQUEST_IMAGE_CAPTURE:
if (takenImageUri != null) {
Uri imagePath =getRealPathFromURI(takenImageUri,this));
}
}
}
}
rather than looping for 4 times, why not make each imageView an OnClickListener to get the image one by one?

Sharing Image via Intent failed

I am trying to capture image and then share it with apps.
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
//start the camera and capture an image
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
//convert captured Image from Intent form to URI
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
startActivity(shareIntent);
//share the image
}
}
But when I run this code, the image doesn't get shared. Is there a bug in my code?
Is there any other way to share an image without saving it in memory?
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
try {
InputStream stream = getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
I would like to thank Alexander for helping find the solution.
Here is the working code -
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Intent.EXTRA_STREAM,
Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
(Bitmap) data.getExtras().get("data"), "title", null)
))
.setType("image/jpeg");
startActivity(intent);
}
}

Android onactivityresult() not being called in fragment

This is my code for calling onactivity result. I am using a dialog which prompts to pick image from gallery or from camera. The same code is working in activity but is not working in fragments. I have tried all the previous answers on stackoverflow. Please help
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Pick from Gallery",
"Take from Camera" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 250);
intent.putExtra("outputY", 250);
try {
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(
intent,
"Complete action using"),
PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
}
break;
case 1:
Intent takePictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent
.resolveActivity(getActivity()
.getPackageManager()) != null) {
startActivityForResult(
takePictureIntent,
PICK_FROM_CAMERA);
}
break;
default:
break;
}
}
});
builder.show();
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
try {
if (requestCode == PICK_FROM_GALLERY) {
System.out.print("ho ja please");
Bundle extras2 = data.getExtras();
if (extras2 != null) {
bitmap = extras2.getParcelable("data");
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
dp.setImageBitmap(output);
}
}
if (requestCode == PICK_FROM_CAMERA) {
Bundle extras = data.getExtras();
Bitmap bitmap1 = (Bitmap) extras.get("data");
bitmap = Bitmap.createScaledBitmap(bitmap1, 250, 250, true);
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
dp.setImageBitmap(output);
}
It is because your alert dialog calls Activity.startActivityForResult instead of Fragment.startActivityForResult. If you want to fix that behaviour use the fragment reference inside your dialog to call startActivityForResult.
UPD: also as mentioned #Ashish Tamrakar don't forget to call super.onActivityResult inside your Activity.onActivityResult method if overridden
You can try by calling startActivityForResult with Activity context i.e.
getActivity().startActivityForResult(Intent.createChooser(
intent,
"Complete action using"),
PICK_FROM_GALLERY);
I am using the below code for showing Image Picker, check this if it helps you -
private static final int SELECT_PICTURE = 1; // Declare this variable
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take picture";
// strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent,
pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
new Intent[] { takePhotoIntent });
getActivity().startActivityForResult(chooserIntent,
SELECT_PICTURE);
Then in your Activity you can use this -
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (imageReturnedIntent != null) {
if (imageReturnedIntent.getData() != null) {
Uri selectedImage = imageReturnedIntent.getData(); // use this URI for getting and updating the fragment
}
}
}

Categories