I have a button which takes a photo, stores the thumbnail in an Imageview, and when the user clicks another button, it needs to attach that image to an email.
Ive followed the "Taking Photos Simply" directions from the Android site, but there is no attachment included. Can somebody see where i am going wrong, and what I need to do to fix it?
My on Activity Result code:
public void onActivityResult(int requestcode, int resultcode, Intent data) {
if (requestcode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultcode == RESULT_OK) {
Bundle bundle = new Bundle();
bundle = data.getExtras();
Bitmap BMB;
BMB = (Bitmap) bundle.get("data");
Hoon_Image.setImageBitmap(BMB);
try {
createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
mDrawable = Hoon_Image.getDrawable();
mBitmap = ((BitmapDrawable) mDrawable).getBitmap();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
my email intent:
if (Witness_response == "Yes"){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"roadsafety.app#shellharbour.nsw.gov.au"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Dob in a Hoon Report (Y)");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Hoon report has been recieved " + emailBody);
emailIntent.putExtra(Intent.EXTRA_STREAM, mCurrentPhotoPath );
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Choose email client..."));
} else if (Witness_response == "No"){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"roadsafety.app#shellharbour.nsw.gov.au"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Dob in a Hoon Report (N)");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Hoon report has been recieved " + emailBody);
emailIntent.putExtra(Intent.EXTRA_STREAM, mCurrentPhotoPath);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Choose email client..."));
}
try this code
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private File f;
public File getAlbumDir()
{
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
"BAC/"
);
// Create directories if needed
if (!storageDir.exists()) {
storageDir.mkdirs();
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName =getAlbumDir().toString() +"/image.jpg";
File image = new File(imageFileName);
return image;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
f = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(photo);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"email id"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
Uri uri = Uri.fromFile(f);
i.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
}
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"me#gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"go on read the emails");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send Mail"));;
and here,
uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), FILENAME));
Related
I want to get image from camera, using
public void LicenseCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, PROFILE_REQUEST_CAMERA);
}
Return bitmap, but it works perfectly. Unfortunately image show as a really small size.
So, i have to keep searching until i get
public void licenseCameraIntent() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri mImageCaptureUri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri1);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, LICENSE_REQUEST_CAMERA);
}
On OnActivityResult data always show null result. How I can fix this issue. It is possible using first solution but return bigger image?
Thanks
while you are capture image from the camera you have created a file for an image that is your image full path so make it globally.
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
and the image file, mCurrentPhotoPath is the full path of image
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
after onActivityResult() you get the image from mCurrentPhotoPath
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For more info, you can check this link Capture Image from Camera and Display in Activity
try this,
public static int REQUEST_CAMERA = 111;
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
code for onStartActivityForResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
_FileName = "image file";
capturePic = null;
file_pdf = null;
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//mImageView.setImageBitmap(imageBitmap);
img_ticket_detail.setImageBitmap(imageBitmap);
capturePic = imageBitmap;
}
}
}
also you can use glide library for show image
I can't take a picture from the camera and then store it as a Bitmap object. I can only find solutions where I get thumbnail as Bitmap. How can I do this?
Here is the code:
public boolean pickImageFromCamera(View View) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try
{
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
photo.delete();
}
catch(Exception e)
{
System.out.println("ERROR TAKING PICTURE");
return false;
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
//start camera intent
activity.startActivityForResult(intent, REQUEST_CODE2);
return true;
}
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
public void pickImageFromFolder(View View) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , REQUEST_CODE);//one can be replaced with any action code
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE2 && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
Bitmap bitmap = null;
this.getContentResolver().notifyChange(mImageUri, null);
ContentResolver cr = this.getContentResolver();
try
{
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
imageView.setImageBitmap(bitmap);
}
catch (Exception e)
{
System.out.println("Failed to load");
}
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
this.UPLOAD_URL = Config.webSiteUrl + "?action=uploadFile&username=" + this.username + "&password=" + this.password + "&baustelleid=" + Fotos.this.baustelleid;
if(bitmap != null) {
uploadImage(bitmap, this.UPLOAD_URL);
}
} catch (Exception e) {
System.out.println("Fehler 1");
}
super.onActivityResult(requestCode, resultCode, data);
}
It ends up with System.out.println("ERROR TAKING PICTURE"); It seems like there is no permission to write the storage. How can I change this?
Call this method in button etc. after that get bitmap onActivityResult
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
File photoThumbnailFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.yourfileprovider",
photoFile);
photoThumbnailURI = FileProvider.getUriForFile(this,
"com.example.yourfileprovider",
photoThumbnailFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
This method will Create file
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
This method will happen when the camera is done taking the picture
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoURI);
mImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You will get a bitmap, but you can get the whole one, not just the thumbnail.
Have you tried this answer ? https://stackoverflow.com/a/6449092/4127441
I'm trying to take a photo with the camera and in the activity result method I want to save it and launch a new activity to display the photo from where I saved it, but the imageView stay empty, I used the code from android developer
and here is my code:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile () throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
//Bundle extras = data.getExtras();
// Bitmap imageBitmap =(Bitmap) extras.get("data");
Intent formIntent= new Intent(MainActivity.this,FormActivity.class);
// formIntent.putExtra("img",imageBitmap);
formIntent.putExtra("path",mCurrentPhotoPath);
startActivity(formIntent);
}
}
the activity that shoud display the photo
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
String path = getIntent().getStringExtra("path");
mImageView = (ImageView) findViewById(R.id.imageView);
File imgFile = new File(path);
Toast.makeText(this, path, Toast.LENGTH_LONG).show();
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mImageView.setImageBitmap(myBitmap);
}
}
I need to take a picture with the camera, save the picture, show in ImageView and when I click the Imageview show in fullscreen mode .
In the future will need to send the picture to the internet.
This is what I've done :
public void captureImage(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
imgView = (ImageView) findViewById(R.id.formRegister_picture);
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case CAMERA_PIC_REQUEST:
if(resultCode==RESULT_OK){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imgView.setImageBitmap(thumbnail);
}
}
}
You can invoke camera Activity by adding these lines in your code :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
private static int RESULT_IMAGE_CLICK = 1;
cameraImageUri = getOutputMediaFileUri(1);
// set the image file name
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
startActivityForResult(intent, RESULT_IMAGE_CLICK);
Now create file Uri because in some android phones you will get null data in return
so here is the method to get the image URI :
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// Check that the SDCard is mounted
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), Environment.DIRECTORY_PICTURES);
// Create the storage directory(MyCameraVideo) if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Item Attachment",
"Failed to create directory MyCameraVideo.");
return null;
}
}
java.util.Date date = new java.util.Date();
String timeStamp = getTimeStamp();
File mediaFile;
if (type == 1) {
// For unique video file name appending current timeStamp with file
// name
mediaFile = new File(mediaStorageDir.getPath() + File.separator +abc+ ".jpg");
} else {
return null;
}
return mediaFile;
}
For retrieving clicked image :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == RESULT_IMAGE_CLICK) {
// Here you have the ImagePath which you can set to you image view
Log.e("Image Name", cameraImageUri.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(cameraImageUri.getPath());
yourImageView.setImageBitmap(myBitmap);
// For further image Upload i suppose your method for image upload is UploadImage
File imageFile = new File(cameraImageUri.getPath());
uploadImage(imageFile);
}
}
}
Since there is no proper solution for this, I will put here what I have put together that is working and correct.
ImageButton takepic = (ImageButton) returnView.findViewById(R.id.takepic);
takepic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { Intent intent = new Intent();
addPhoto();
}
});
Android Manifest :
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
Android Manifest again at the top :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
External res/xml/file_paths.xml file:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" />
</paths>
CreateImageFile Function
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
AddPhoto Function
private void addPhoto() {
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getActivity().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.MEDIA_IGNORE_FILENAME, ".nomedia");
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "profileimg");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(chooserIntent, 100);}
}
On activity callback
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
try {
Bundle extras = data.getExtras();
Uri uri = data.getData();
ImageButton takepic = (ImageButton) returnView.findViewById(R.id.takepic);
if (extras!=null){
Bitmap imageBitmap = (Bitmap) extras.get("data");
Log.d(TAG, "onActivityResult: "+mCurrentPhotoPath);
takepic.setImageBitmap(imageBitmap);
}
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String idx = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContext().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{idx}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
takepic.setImageBitmap(bitmap);
Toast.makeText(getContext(), "Uploading In Progress",
Toast.LENGTH_LONG);
}catch(Exception e){
e.getMessage();
}
}}
Try this, to save image to file explorer:
public void captureImage(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "image.png");
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode== Activity.RESULT_OK){
f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("image.png")) {
f = temp;
imagePath= f.getAbsolutePath();
Bitmap thumbnail= BitmapFactory.decodeFile(f.getAbsolutePath(), options);
imgView.setImageBitmap(thumbnail);
}
You can fetch image from path "imagePath" whenever you have to display it.
((HomeActivity) getActivity()).contactus
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendEmail();
}
});
((HomeActivity) getActivity()).attachmentimageview
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
MY_INTENT_CLICK);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == MY_INTENT_CLICK) {
if (null == data)
return;
String selectedImagePath;
Uri selectedImageUri = data.getData();
// MEDIA GALLERY
selectedImagePath = ImageFilePath.getPath(
getActivity(), selectedImageUri);
Log.i("Image File Path", "" + selectedImagePath);
// txta.setText("File Path : \n" + selectedImagePath);
}
}
}
private void sendEmail() {
try {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[] { "Enter email" };
emailIntent
.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
emailIntent
.putExtra(
Intent.EXTRA_EMAIL,
new String[] { "anilkumar#softageindia.com,danyalozair#gmail.com" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Feedback");
emailIntent.putExtra(Intent.EXTRA_STREAM, selectedImagePath );
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
Html.fromHtml(""));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "HI"
+ "\n\n" + contactustext.getText().toString());
emailIntent.setType("message/rfc822");
startActivity(emailIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
This is my code i want to attach file from Sd card or gallery i am using given code i am able to get path from galley But when i click on contact Us Button then it same work to get file directory if we not use attachment then it work properly with text please check where am doing wrong and how to fix it please suggest me actully i want send some text and also with attachment send via gmail when i click on button contact us it redirect to attachment and text to gmail then we can send it .
you can attach file as :
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Please find attachment");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+"you file's path"));
startActivity(Intent.createChooser(sharingIntent, "Attach using..."));
Firstly, create this method in your Activity or Fragment outside of onCreate
public static void getVcardString() {
String path = null;
String vfile = null;
vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
phones.moveToFirst();
Log.i("Number of contacts", "cursorCount" +phones.getCount());
for(int i =0;i<phones.getCount();i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", " " +lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
filevcf = new File(path);
Log.i("file", "file" +filevcf);
}catch(Exception e1) {
e1.printStackTrace();
}
}
Log.i("TAG", "No Contacts in Your Phone");
}
and call it inside onCreate like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getVcardString();
}
And now again, create a new method to send Email outside of onCreate like :
protected void data() {
File filelocation = filevcf ;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(Intent.EXTRA_EMAIL, "mail#gmail.com" );
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation.getAbsolutePath()));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
And call this data() method onClick of your send email button like :
data();
Please let me know if you get any problem now.