how to capture image from camera, in fragment, - android

I am new to Android, and I have done lots of training but the image does not load from the camera. Below is my code for capturing image from camera or gallery:
public void showDiloag(){
Dialog dialog = new Dialog(getActivity());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Gallery", "Camera" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent
.createChooser(
intent,
"Choose a Picture");
getAcitivity.startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
break;
case 1:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
cameraIntent,
ACTION_REQUEST_CAMERA);
break;
default:
break;
}
}
});
builder.show();
dialog.dismiss();
}
And for display that photo:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == Utils.ACTION_REQUEST_GALLERY) {
// System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
String tempPath = JuiceAppUtility.getPath(
selectedImageUri, getActivity());
Bitmap bm = JuiceAppUtility
.decodeFileFromPath(tempPath);
imgJuice.setImageBitmap(bm);
} else if (requestCode == Utils.ACTION_REQUEST_CAMERA) {
Bitmap photo = (Bitmap) data.getExtras()
.get("data");
imgJuice.setImageBitmap(photo);
}
}
}
Also image is captured from camera and choose from gallery but it will not load in ImageView. Can anybody help me please?

Ya i found your problem
just remove below line and
getAcitivity.startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
and write down below code
startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
just remove getActivity

FRAGMENT SIDE
btnimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
private void showPictureDialog(){android.app.AlertDialog.Builder pictureDialog = new android.app.AlertDialog.Builder(getActivity());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// choosePhotoFromGallary();
choosePhotoFromGallary();
break;
case 1:
// takePhotoFromCamera();
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void takePhotoFromCamera() {
Uri resultUri;
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
resultUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, resultUri);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent, 22);
}
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 11);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK)
{
if (requestCode == 11) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
// String path = saveImage(bitmap);
// Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
iv_froncnic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
{
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
}
}
}
In parent ACTIVITY
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode==this.RESULT_OK){
super.onActivityResult(requestCode, resultCode, data);
setResult(RESULT_OK, data);
}
}

Related

Gallery permission and Camera Permission not working

i was adding profile picture option in my application from camera and gallery All was working well till i tried to select a picture and display it in my image circulerView .when i select a picture to set in my imageCirculerView , it doesn't set in the imageCirculerView and no error is even showing ..So i literally don't know where i did the mistake
private void pickFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select picture"), IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera() {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "Temp_image Title");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp_desc Desctription");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE);
}
profilepicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//pick a image
showImagePickDialog();
}
});
private void showImagePickDialog() {
//options to display in dialoge
String[] options = {"Camera", "Dialoge"};
//dialoge
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick Image").setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
//Camera Clicked
if (checkCameraPermission()) {
//Camera request allowed
pickFromCamera();
} else {
//not allowed Request
requestCameraPermission();
}
} else {
//gallery Clicked
if (checkStoragePermission()) {
//Storage request allowed
pickFromGallery();
} else {
//not allowed Request
requestStoragePermission();
}
}
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == RESULT_OK){
if(requestCode== IMAGE_PICK_GALLERY_CODE){
//getPicked image
image_uri = data.getData();
//settoimageView
profilepicture.setImageURI(image_uri);
}else if(requestCode== IMAGE_PICK_CAMERA_CODE){
//settoimageView
profilepicture.setImageURI(image_uri);}
}
super.onActivityResult(requestCode, resultCode, data);
}

Selected from gallery or camera photos not displaying in the ImageView

Camera taken photo or selected photo is not displaying in ImageView. I'm using the following code:
private void attachFile() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(mContext);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Photo"), SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA && data != null) {
Log.d(TAG, "onActivityResult: done take photo");
Uri mImageCaptureUri = data.getData();
imageView.setImageURI(mImageCaptureUri);
/*Bundle bundle = data.getExtras();
final Bitmap bitmap = (Bitmap) bundle.get("data");
mOnphotoSelectedListener.getImageBitmap(bitmap);*/
} else if (requestCode == SELECT_FILE) {
Uri selectImageUri = data.getData();
mOnphotoSelectedListener.getImagePath(selectImageUri);
//imageView.setImageURI(selectImageUri);
//Picasso.with(mContext).load(selectImageUri).into(imageView);
//Picasso.with(this).load(selectImageUri).into(imageView);
}
}
}
i have this code i hope it will work for you its correct working
i set onclick for ImageProfile and i give to user picture + crop
i hope it will work for u
private void mImage_profileOnclick() {
int persmissonCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
if (persmissonCheck == PackageManager.PERMISSION_DENIED) {
Req();
}else {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_open_device);
Button pic, gal;
pic = (Button) dialog.findViewById(R.id.pick);
gal = (Button) dialog.findViewById(R.id.gallery);
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
dialog.cancel();
dialog.dismiss();
}
});
gal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialog.findViewById(R.id.cropImageView);
Button button = (Button) dialog.findViewById(R.id.bac);
cropImageView.setImageBitmap(imageBitmap);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mImage_profile.setImageBitmap(cropImageView.getCroppedImage());
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Dialog dialogs = new Dialog(getActivity());
dialogs.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialogs.findViewById(R.id.cropImageView);
cropImageView.setImageUriAsync(selectedImage);
Button button = (Button) dialogs.findViewById(R.id.bac);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap cropped = cropImageView.getCroppedImage();
mImage_profile.setImageBitmap(cropped);
dialogs.cancel();
dialogs.dismiss();
}
});
//dialogs.create();
dialogs.show();
}
break;
}
}
//#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void Req() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "شما مجوز استفاده از دوربین یا هر چیز دیگر را به برنامه نداده اید", Toast.LENGTH_SHORT).show();
}
else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
mImage_profileOnclick();
} }
Used below code inside the onActivityResult
if (requestCode == Activity.RESULT_OK) {
File user_dp;
if (requestCode == REQUEST_CAMERA && data != null) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
user_dp = destination;
//update_profilepic is ImageView reference
Picasso.with(getContext()).load(user_dp).into(update_profilepic);
} else if (requestCode == SELECT_FILE) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
//ivImage is image reference
ivImage.setImageBitmap(bm);
}
}
}
Instead of resultCode I have requestCode on the first line inside the if statement.

Getting an image from gallery and camera (Android Studio)

I am working on an project where the user can change their profile picture either by taking a picture or selecting an image from Gallery. Despite following multiple tutorials, the code they use does not work for me. Whenever I select Camera on the Dialog Box, it goes to Gallery then Camera. Likewise when I select Gallery on the Dialog Box, it does go to Gallery but it will still go to Camera before displaying the image on the Image View. Is it because I am using Android Lollipop? I am not really sure too.
How can I get this fixed?
package com.example.user.imagestuff;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
String[] Items;
ImageView mImageView;
Button mButton;
final int bmpHeight = 160;
final int bmpWidth = 160;
static final int CAMERA_CODE = 1;
static final int GALLERY_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.mImageView);
mButton = (Button) findViewById(R.id.mButton);
Items = getResources().getStringArray(R.array.DialogItems);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageOnClick(v);
}
});
}
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for(int i=0; i < Items.length; i++){
if (Items[i].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[i].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
switch(requestCode){
case 1:
Log.i("CameraCode",""+CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
mImageView.setImageBitmap(resized);
case 0:
Log.i("GalleryCode",""+requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
}
}
}
}
Because you are using for loop for checking Camera and Gallary Strings. You need to remove for loop and try ike below code
And also you missing break in your swith case
final CharSequence[] items = {"Camera", "Gallery"}
if (items[item].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (items[item].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
Second Option
You can also put break; keyword for breaking your for loop when your condition match
You are opening an intent in for loop and there is another mistake is you are not breaking the case in your switch case. Use break in your switch case
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
switch(requestCode){
case 1:
Log.i("CameraCode",""+CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
mImageView.setImageBitmap(resized);
break;
case 0:
Log.i("GalleryCode",""+requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
break;
}
}
This works fine for me.
public static final int CAMERA_PERMISSION =100;
public static final int REQUEST_IMAGE_CAPTURE =101;
public static final int READ_STORAGE_PERMISSION =102;
public static final int REQUEST_IMAGE_PICK =103 ;
private Dialog mCameraDialog;
private Uri mImageURI;
/**
* Method to show list dialog to choose photo form gallery or camera.
*/
private void showChoosePhotoDialog() {
mCameraDialog.setContentView(R.layout.dialog_choose_photo);
if(mCameraDialog.getWindow()!=null)
mCameraDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mCameraDialog.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCameraDialog.dismiss();
onCameraOptionSelected();
}
});
mCameraDialog.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCameraDialog.dismiss();
onGalleryOptionSelected();
}
});
mCameraDialog.show();
}
/**
* Method to open gallery.
*/
private void onGalleryOptionSelected() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentGallery, REQUEST_IMAGE_PICK);
overridePendingTransition(R.anim.push_left_right, R.anim.push_right_left);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_STORAGE_PERMISSION);
}
}
/**
* Method to open chooser.
*/
private void onCameraOptionSelected() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
CAMERA_PERMISSION);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION);
}
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
CAMERA_PERMISSION);
} else {
mImageURI = Uri.parse(AppUtils.getFilename());
startActivityForResult(AppUtils.getCameraChooserIntent(EditProfileActivity.this, mImageURI + ""),
REQUEST_IMAGE_CAPTURE);
}
} else {
mImageURI = Uri.parse(AppUtils.getFilename());
startActivityForResult(AppUtils.getCameraChooserIntent(this, mImageURI + ""),
REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION:
int j = 0;
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED)
j = 1;
}
if (j == 1) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) || (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA))) {
// Toast.makeText(this, R.string.s_camera_permission, Toast.LENGTH_SHORT).show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) || !ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Open phone settings page.
// Toast.makeText(this, getString(R.string.s_app_needs_camera_permission), Toast.LENGTH_SHORT).show();
}
} else
onCameraOptionSelected();
break;
case READ_STORAGE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
onGalleryOptionSelected();
else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Toast.makeText(this, getString(R.string.s_storage_permission), Toast.LENGTH_SHORT).show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Open Phone Settings
}
}
}
Please Replace your code
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for(int i=0; i < Items.length; i++){
if (Items[i].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[i].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
}
});
builder.show();
}
To
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Items[which].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[which].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
});
builder.show();
}
you didnt use break statement thats why its moving to next statement.
just use break statement when you are firing an intent
public void ImageOnClick (View v){
Log.i("OnClick", "True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < Items.length; i++) {
if (Items[i].equals("Camera")) {
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (CameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(CameraIntent, CAMERA_CODE);
}
break;
} else if (Items[i].equals("Gallery")) {
Log.i("GalleryCode", "" + GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent, GALLERY_CODE);
}
break;
}
}
});
builder.show();
}
To make it efficient use position value, when you set onclickListener it returns one int variable which is position of list which is clicked. In your case its int which So you can simply use
public void ImageOnClick (View v){
Log.i("OnClick", "True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Items[which].equals("Camera")) {
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (CameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(CameraIntent, CAMERA_CODE);
}
break;
} else if (Items[which].equals("Gallery")) {
Log.i("GalleryCode", "" + GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent, GALLERY_CODE);
}
break;
}
});
builder.show();
}
Also in OnActivityResult method use break statement otherwise it will both cases
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case 1:
Log.i("CameraCode", "" + CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, true);
mImageView.setImageBitmap(resized);
break;
case 0:
Log.i("GalleryCode", "" + requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
break;
}
}
}

Android won't allow me to get a photo from the gallery

Can anyone please explain to me why this code allows me to take a photo and show it in an image button but not when i try to get the picture from the gallery . It doesn't show any errors .
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
final AlertDialog.Builder constructor = new AlertDialog.Builder(this);
constructor.setTitle("Añadir Foto!");
constructor.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
PROFILE_PIC_COUNT = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
PROFILE_PIC_COUNT = 1;
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,SELECT_FILE);
} else if (items[item].equals("Cancel")) {
PROFILE_PIC_COUNT = 0;
dialog.dismiss();
}
}
});
img_header.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
constructor.show();
}
});
This is the onActivityResult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent_imagen) {
super.onActivityResult(requestCode, resultCode, intent_imagen);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
setFoto(intent_imagen);
}
break;
case 1:
if(resultCode == RESULT_OK){
setFoto(intent_imagen);
}
break;
}
}
private void setFoto(Intent intent_imagen) {
Bitmap foto;
foto=getCroppedBitmap(Bitmap.createScaledBitmap((Bitmap)intent_imagen.getExtras().get("data"), 190, 165, true));
img_header.setForeground(null);
img_header.setImageBitmap(foto);
}

Camera and gallery crop options

I am using camera option in my app but it works some devices only. Also I need crop options.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {
mImageCaptureUri = data.getData();
System.out.println("Gallery Image URI : "+mImageCaptureUri);
CropingIMG();
}
}
To fix camera issue, I have used following methods
CameraIntentHelper
onSaveInstanceState
onRestoreInstanceState
onActivityResult
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoSuiteActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
if (mCameraIntentHelper != null) {
mCameraIntentHelper.startCameraIntent();
} else {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.png";
File imageFile = new File(imageFilePath);
picUri = Uri.fromFile(imageFile); // convert path to Uri
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(takePictureIntent, CAMERA_CAPTURE);
}
} else if (options[item].equals("Choose from Gallery")) {
Toast.makeText(PhotoSuiteActivity.this, "Not yet Ready...!", Toast.LENGTH_SHORT).show();
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
mImageCaptureUri = photoUri;
Bitmap photo = BitmapHelper.readBitmap(PhotoSuiteActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
imageView.setImageBitmap(photo);
CropingIMG();
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, PhotoSuiteActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}

Categories

Resources