So I used this to open my image choose upon button click
//Open image chooser
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
and used onActivityResult
private final static int SELECT_PHOTO = 12345;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("CALLED", "OnActivity Result");
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
Log.e("img", "It worked");
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
In logcat, OnactivityResult is not being called, and I cant figure out why. So when I click the button, the image chooser pops up, I choose an image, and then it exits back to the main screen.
Am I missing something, as I've followed others' code but I still get the same thing
Give this a try:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Select:"), SELECT_PHOTO);
Related
Hello
I am working on an app that can send an email with an attachment.
I am completly stuck. I am unable to attach an attachment to my app.
I press the attachment button and I can choose a picture but every time I press the picture, the app crash.
The LogCat gives me a NullPointerException and saying the problem is at "Log.e("Attachment Path: ", attachmentFile);" so my guess is that something goes wrong when I try to save it since the attachmentFile is null.
I can not figure out why the attachmentFile is null since that is the reason I get NullPointerException.
I appreciate every help I can get.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null,null,null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
attachmentFile = cursor.getString(columnIndex);
Log.e("Attachment Path: ", attachmentFile);
URI = Uri.parse("file://" + attachmentFile);
cursor.close();
}
}
Here is the crash
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=101, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:39 flg=0x1 }} to activity {com.example.william.mailappen/com.example.william.mailappen.MainMail}: java.lang.NullPointerException: println needs a message
UPDATE
I use this method to open the picture gallery
public void pictureGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
2:nd UPDATE
Dont know if I am doing it correctly or if this is the right way to go compared to the other method above or is it something super clear that I am missing? The URI is still null...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK)
{
File filelocation = new File(Environment.getExternalStorageDirectory(), "picture.jpg");
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("image/*");
String to[] = {mailAdressTextField.getText().toString()};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, messageTextField.getText().toString());
}
I used something like this. Forked fine
File filelocation = new File(Environment.getExternalStorageDirectory(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {"email#email.com"};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your string");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
EDIT
filename is the name of your file with postfix (for example .jpg)
I'm making an Android application in Android studio where the user can take a photo and save it into a new folder in their gallery. Currently the application takes the pictures fine but doesn't save the image into the new "SOC" folder in my gallery. I'm not getting any errors and I have no idea why it's not saving the image. Any help would be appreciated.
My code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I think you must manually add your new photo Uri to Media Content Provider.
take a look here
Call this method in your Activity for result
protected void addPhotoToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(getCurrentPhotoPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
you should save the photo path before launching the intent and then getCurrentPhotoPath() must get that path
In the app I am building, the user selects a picture from gallery and the path is saved in Shared Preferences. I then want to retrieve this picture from the stored path but it doesn't work. The image is an ImageButton, which the user clicks in order to select picture from Gallery.
The code I have to retrieve the picture and "put" on the ImageButton is:
This code does actually work now, put it here in case it helps others.
File imgFile = new File(sharedpreferences.getString(Path, LOCATION_SERVICE));
if(imgFile.exists())
{
Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageButton img=(ImageButton)findViewById(R.id.AddPic);
img.setImageBitmap(b);
}
I know the path is correct, but I am not able to retrieve the picture and put it on the ImageButton.
Below is the code where the user clicks on the ImageButton, and selects a picture from the gallery and the path of that picture is stored within the sharedPreferences:
imgButton = (ImageButton) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(GaleryIntent, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
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 SelectedCursor = getContentResolver().query(SelectedImage, FilePathColumn, null, null, null);
SelectedCursor.moveToFirst();
int columnIndex = SelectedCursor.getColumnIndex(FilePathColumn[0]);
String picturePath = SelectedCursor.getString(columnIndex);
SelectedCursor.close();
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Editor editor = sharedpreferences.edit();
editor.putString(Path, picturePath);
editor.commit();
}
}
What am I doing wrong?
Thanks very much!
Folks.
I'm facing a strange issue here. I have an application that you can select an image from Gallery or Camera in a button click. All went well except whenever i select any picture from my camera folder the application just crashed. Hereunder my code
case R.id.camera:
AlertDialog.Builder builder = new AlertDialog.Builder(Splash.this);
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Gallery", "Camera" },
new DialogInterface.OnClickListener() {
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");
startActivityForResult(chooser,
ACTION_REQUEST_GALLERY);
break;
case 1:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String mImageCaptureUri = null;
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
startActivityForResult(cameraIntent,
ACTION_REQUEST_CAMERA);
break;
}
}
});
builder.show();
break;
Activity for result :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri selectedImageUri;
selectedImageUri = data == null ? null : data.getData();
cap.setImageURI(selectedImageUri);
break;
case ACTION_REQUEST_CAMERA:
Bitmap photo = (Bitmap) data.getExtras().get("data");
cap.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
Toast.makeText(getApplicationContext(),
finalFile.getAbsolutePath(), 4000).show();
break;
}
}
}
It is hard to say without logcat, but most probable reason is large image size, photos taken with camera are to big to show without scaling, this is the reason that some images you tried works while camera images don't. Try to google: scaling larg bitmaps google developers and you will find official post
I am using the Below Code for get the image and video from gallery, but can't Detect the photo or video selection from library
Intent intent = new Intent();
intent.setType("video/*,image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_VIDEO);
Did you used onActivityResult to get the selected image ? code will be like below.
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.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); // file path of selected image
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
yourimgView.setImageBitmap(yourSelectedImage);
}
}
}
For intent you can try with this.
final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);