I'm trying to launch an intent to pick a image from the camera or the android's gallery. I checked THIS post and currently my code is near to work:
private Intent getPickIntent() {
final List<Intent> intents = new ArrayList<Intent>();
if (allowCamera) {
setCameraIntents(intents, cameraOutputUri);
}
if (allowGallery) {
intents.add(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
}
if (intents.isEmpty()) return null;
Intent result = Intent.createChooser(intents.remove(0), null);
if (!intents.isEmpty()) {
result.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new Parcelable[] {}));
}
return result;
}
private void setCameraIntents(List<Intent> cameraIntents, Uri output) {
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = context.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, output);
cameraIntents.add(intent);
}
}
When I set allowCamera=true it works correctly.
When I set allowGallery=true it shows the following chooser:
But if I set allowCamera=true and allowGallery =true the chooser shown is:
And if you select Android System then the first chooser is shown.
I'd like the chooser to be something like:
How can I "expand" the Android System option?
Intent galleryintent = new Intent(Intent.ACTION_GET_CONTENT, null);
galleryintent.setType("image/*");
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INTENT, galleryintent);
chooser.putExtra(Intent.EXTRA_TITLE, "Select from:");
Intent[] intentArray = { cameraIntent };
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooser, REQUEST_PIC);
In your linked post you can find the solution. The difference to your code is how the gallery intent is created:
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
Not with ACTION_PICK how you did but with ACTION_GET_CONTENT. It seems that if a single ACTION_PICK is in the list (a "container intent"), the system traverses it to display the content of the pick, but as soon you include the camera intent it can't traverse anymore (since there is one direct intent and one container intent).
In the comment of this answer you find the difference between ACTION_PICK and ACTION_GET_CONTENT.
There are some solutions available which recommend to use a custom dialog. But this dialog will not have the standards icons (see develper docs here). So I recommend to stay at your solution and just fix the hierarchie issue.
## Intent to choose between Camera and Gallery Heading and can crop image after capturing from camera ##
public void captureImageCameraOrGallery() {
final CharSequence[] options = { "Take photo", "Choose from library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Post_activity.this);
builder.setTitle("Select");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (options[which].equals("Take photo")) {
try {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
} catch (ActivityNotFoundException ex) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
}
} else if (options[which].equals("Choose from library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
} else if (options[which].equals("Cancel")) {
dialog.dismiss();
}
}
});
dialog = builder.create();
dialog.getWindow().getAttributes().windowAnimations = R.style.dialog_animation;
dialog.show();
}
public void onActivityResult(int requestcode, int resultcode, Intent intent) {
super.onActivityResult(requestcode, resultcode, intent);
if (resultcode == RESULT_OK) {
if (requestcode == TAKE_PICTURE) {
picUri = intent.getData();
startCropImage();
} else if (requestcode == PIC_CROP) {
Bitmap photo = (Bitmap) intent.getExtras().get("data");
Drawable drawable = new BitmapDrawable(photo);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
} else if (requestcode == ACTIVITY_SELECT_IMAGE) {
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable = new BitmapDrawable(thumbnail);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
}
}
private void startCropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
} catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast
.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
You may need to create a custom dialog for this:
Here is the code for the method which is to be called when the user clicks on a particular button:
private void ChooseGallerOrCamera() {
final CharSequence[] items = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "MyImage.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
And the code for handling onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bitmap mBitmap;
if (requestCode == REQUEST_CAMERA) {
File camFile = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : camFile.listFiles()) {
if (temp.getName().equals("MyImage.jpg")) {
camFile = temp;
break;
}
}
try {
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
mBitmap = BitmapFactory.decodeFile(camFile.getAbsolutePath(),
btmapOptions);
//Here you have the bitmap of the image from camera
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, MyActivity.this);
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
mBitmap = BitmapFactory.decodeFile(tempPath, btmapOptions);
//Here you have the bitmap of the image from gallery
}
}
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
EDIT:
Try Using this:
private void letUserTakeUserTakePicture() {
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(getTempFile(getActivity())));
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takePhotoIntent});
startActivityForResult(chooserIntent, Values.REQ_CODE_TAKEPICTURE);
}
Your code already very achieve the goal. Just exchange the gallery and camera add order.
if (allowGallery) {
intents.add(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
}
if (allowCamera) {
setCameraIntents(intents, cameraOutputUri);
}
Here's my test result. Appearance difference since my OS is Android Nougat(7.0)
The first screenshot is in your order, the second is after exchange. Just like you said, in first situation, click the system logo will show gallery items.
Intent for showing camera and video files in activity chooser:
Intent galleryintent = new Intent(Intent.ACTION_GET_CONTENT, null);
galleryintent.setType("video/*");
Intent cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INTENT, galleryintent);
chooser.putExtra(Intent.EXTRA_TITLE, "Select from:");
Intent[] intentArray = { cameraIntent };
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooser, REQUEST_VIDEO_CAPTURE);
Related
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
After selecting/capturing the image i need to crop the image.
I already done this one.but the problem is when i am switching to the android latest version(kitkat) crop intent is not working properly.
My Code
private void picPhoto() {
Intent pickIntent = new Intent();
if (Build.VERSION.SDK_INT < 19) {
pickIntent.setType("image/jpeg");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
pickIntent.putExtra("crop", "true");
} else {
pickIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickIntent.setType("image/jpeg");
pickIntent.putExtra("crop", "true");
}
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileDirectory());
takePhotoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
String pickTitle = "Select or take a new Picture";
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[]{takePhotoIntent}
);
startActivityForResult(chooserIntent, PICK_IMAGE);
}
Can any one help with me an example ?
I used this method to crop a pic which was working in kitkat too
#Override
public void onActivityResult(int requestCode, int resultCode,
final Intent data) {
if (resultCode == Activity.RESULT_OK&&requestCode==1) {
performCrop(image_uri);
}
}
private void performCrop(Uri picUri) {
thePic = null;
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// // indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// // // indicate output X and Y
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 3);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(getActivity(),
"This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
} catch (OutOfMemoryError e) {
System.out.println("out of memoryyy");
} catch (Exception e) {
Display display = getActivity().getWindowManager()
.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// // indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// // indicate output X and Y
cropIntent.putExtra("outputX", width);
cropIntent.putExtra("outputY", 200);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 3);
}
}
So this is it..
private void picPhoto() {
Intent pickIntent = new Intent();
if (Build.VERSION.SDK_INT < 19) {
pickIntent.setType("image/jpeg");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
} else {
pickIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickIntent.setType("image/jpeg");
}
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileDirectory());
takePhotoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
String pickTitle = "Select or take a new Picture";
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[]{takePhotoIntent}
);
startActivityForResult(chooserIntent, PICK_IMAGE);
}
All features will work Api >14 ie , Android 4.0 (ICE_CREAM_SANDWICH).
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String wholeID = DocumentsContract.getDocumentId(_uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
croppedPath = filePath;
} else {
//User had pick an image.
Cursor cursor = getActivity().getContentResolver().query(_uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
//Link to the image
final String imageFilePath = cursor.getString(0);
croppedPath = imageFilePath;
cursor.close();
}
if (croppedPath != null) {
cropIntent(croppedPath, 5);
}
} else if (requestCode != 4 && requestCode == PICK_IMAGE && data == null) {
cropIntent(getFileDirectory().getPath(), 4);
} else if (requestCode == 4) {
editPhoto1.setImageBitmap(null);
if (bmp != null) {
bmp.recycle();
}
setImagePicked(getFileDirectory().getPath(), 0);
} else if (requestCode == 5) {
if (croppedPath != null) {
editPhoto1.setImageBitmap(null);
if (bmp != null) {
bmp.recycle();
}
setImagePicked(getFileDirectory().getPath(), 0);
croppedPath = null;
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Crop method
private void cropIntent(String fileToCrop, int requestCode) {
Uri filePath = Uri.fromFile(new File(fileToCrop));
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(filePath, "image/*");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileDirectory());
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, requestCode);
//start the activity - we handle returning in onActivityResult
}
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
}
}
}
I am making an android application in which i have to select image from gallery by clicking a button and then display it in another activity with two text fields, the problem is i am able to open the gallery and select image from it but i am not able to display image in another activity...
here is my code...
PictureOptions.java
public void buttonGalleryOpen(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String [] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
PictureOptions.xml
<Button
android:id="#+id/buttonGalleryOpen"
android:layout_width="fill_parent"
android:layout_height="66dp"
android:layout_weight="0.34"
android:onClick="buttonGalleryOpen"
android:text="#string/button_gallery_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageBitmap(selectedphoto);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="200dp"
android:layout_height="200dp" />
All things are working fine and second activity(ShowImage) is also opening except that no iamge is displying....dont know why..?HELP
This line in your code does not make sense:
intent.putExtra("data", "selectedphoto");
You are adding here string "selectedphoto" which is in no way connected to selectedphoto variable you initialised earlier. You could put your bitmap to intent extra as byte array but this is inefficient, especially when the image is large.
Instead of passing bitmap to ShowImage activity, pass your URI and then retrieve actual bitmap in ShowImage activity exactly as you do now in your PictureOptions activity.
intent.setData( uri );
In your ShowImage activity do:
URI imageUri = getIntent().getData();
Yo have a typo in intent.putExtra("data", "selectedphoto");, you are passing a String not the bitmap. Change it in
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
removing the double quote from selectedphoto
private void selectImage() {
final CharSequence[] items = { "Photo Library", "Camera", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select");
Utils.hideSoftKeyboard(getActivity());
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Camera")) {
// camera intent
} else if (items[item].equals("Photo Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(tempPath, btmapOptions);
resized = Bitmap.createScaledBitmap(bitmap,
(int) (bitmap.getWidth() * 0.8),
(int) (bitmap.getHeight() * 0.8), true);
profileEditImageView.setImageBitmap(resized);
}
}
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I want to make an app, when i press on a certain button i want to open the cam then capture the image and after i capture it.
I want to open this image in a new activity, putting this image in this new activity in addition to two buttons one to delete it and the other one to save it in a certain directory of the tablet.
i use the code to open the cam:
Open_CAM.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
I don't know what can i do after that?
Any help please...
Open_CAM.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent photoPickerIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent,TAKE_PICTURE);}}
private Uri getTempFile()
{
File root = new File(Environment.getExternalStorageDirectory(), "ServiceMySigns");
if (!root.exists())
{
root.mkdirs();
}
final Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR);
int m = c.get(Calendar.MONTH);
int d = c.get(Calendar.DAY_OF_MONTH);
int h = c.get(Calendar.HOUR_OF_DAY);
int mi = c.get(Calendar.MINUTE);
//String filename=""+y+"-"+"-"+(m+1)+"-"+d+" "+h+":"+mi;
String filename=""+System.currentTimeMillis();
File file = new File(root,filename+".jpeg" );
muri = Uri.fromFile(file);
selectedImagePath=muri.getPath();
Log.v("take picture path",selectedImagePath);
return muri;
}
public void onActivityResult(int requestcode,int resultcode ,Intent data)
{
switch(requestcode)
{
case TAKE_PICTURE:
if(resultcode==RESULT_OK)
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize=8;
Bitmap newImage = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(selectedImagePath,o),
150,
150,
false);}}}
After you got bitmap in onActivityResult you can send that bitmap to another activity through intent.
bellow code will help you it will take a picture from camera and set image in to next activity
private void takePicture() {
cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, IMAGE_CAPTURE);
}
// Receive the result from the start Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("onActivityResult", "we r in onActivityResult");
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case IMAGE_CAPTURE:
File dir = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File output = new File(dir, "camerascript.png");
cPath = output.getAbsolutePath();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(output));
Intent capIntent = new Intent(yourcurrentActivity.this,
yournextActivity.class);
capIntent.putExtra("gallery", cPath);
startActivity(capIntent);
break;
default:
break;
}
}
}
After that get the intnet extra data in to yournextAactivity where you would like to set a captured image.
ImageView imageView = (ImageView)findViewById(R.id.imgView);
String fileString = getIntent().getStringExtra("gallery");
imageView.setImageBitmap(BitmapFactory.decodeFile(fileString));