Android Camera, Gallery and Mail Handling - android

I am working on an android project where I click picture from camera or pick from gallery and I need to send that image as an attachment in a mail. Here's my code for getting picture from camera enter code here
public void launchCamera(View view){
gallery.setEnabled(false);
String fileName = "abc.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION," XYZ");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
Here is the code to get Image from Gallery
public void launchGallery(View view){
cameraButton.setEnabled(false);
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE_REQUEST);
Here is the onActivityResult function
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
String imageId = convertImageUriToFile( imageUri,CameraActivity);
}
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filep = cursor.getString(columnIndex);
cursor.close();
}
}
public String convertImageUriToFile ( Uri imageUri, Activity activity ) {
Cursor cursor = null;
int imageID = 0;
try {
/*********** Which columns values want to get *******/
String[] proj = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = getContentResolver().query(imageUri, proj, null, null, null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int columnIndexThumb = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int thumbID = 0;
if (cursor.moveToFirst()) {
imageID = cursor.getInt(columnIndex);
thumbID = cursor.getInt(columnIndexThumb);
filep = cursor.getString(file_ColumnIndex);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return filep;
}
The code for sending email is
public class SendMail
{
private Context context;
private ProgressDialog progressDialog;
public void sending(String filepath, String rec, String bod)
{
// Recipient's email ID needs to be mentioned.
String to = rec;
// Sender's email ID needs to be mentioned
final String from = "abc#gmail.com";
// final String username = "xyz";
final String pass = "qwerty";
// Assuming you are sending email from localhost
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Plant Trees");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(bod);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filepath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filepath);
multipart.addBodyPart(messageBodyPart);
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822");
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
And the code to call the sending function in main activity is
public void sem()
{
SendMail sm=new SendMail();
sm.sending(filep,"abc#gmail.com","xyz");
}
When I am running this as soon as I tap the send button the app crashes
Please help also sorry for the mistakes and large code size but I have just learnt Android and this is my first project. Thanks in Advance

Related

SkImageDecoder::Factory returned null, When i displaying image from sqlite

in my project i want to store image in DB Sqlite, but i have problem when i want to displaying image, please help me, this is my code to select image :
public void bt_UFotoClick(View v)
{
v = Img;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == 1)
{
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = intent.getData();
String selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
imageDetail.setVisibility(View.VISIBLE);
imageDetail.setImageURI(selectedImageUri);
SQLiteDatabase dbUpdate = dbHelper.getWritableDatabase();
byte[] byteImage1 = null;
try {
FileInputStream instream = new FileInputStream(selectedImagePath);
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
dbUpdate.execSQL("update m_item set image = '"+byteImage1+"' where kd='"+Code_I+"'");
System.out.println("Success. ");
System.out.println("Success. " +byteImage1);
} catch (IOException e) {
System.out.println("Error. "+e.getMessage());
}
}
else if (resultCode == RESULT_CANCELED)
{
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
And to Displaying image again i use this code :
SearchDetail = db.rawQuery("SELECT * FROM m_item where kd = '"+GetId+"'",null);
if(SearchDetail .getCount()>=1) {
SearchDetail .moveToFirst();
byte GBR_II[]= SearchDetail.getBlob(SearchDetail.getColumnIndex("image"));
imageDetail.setImageBitmap(BitmapFactory.decodeByteArray(GBR_II, 0,GBR_II.length));
System.out.println("get : "+GBR_II);
}
But image not display and in logcat : 12-09 02:28:50.977: D/skia(561): --- SkImageDecoder::Factory returned null
Thanks,

android: getting contact photo is not working, tried many things but still not working

In android i am trying to get contact data, i got success for number but for contact photo i am facing problem. i got contact photo uri content://com.android.contacts/data/6376/photo but when i am setting it to image view, the image view will blank
/*getting activity result */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
// return from file upload
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
String contactID="";
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.Contacts._ID
//ContactsContract.CommonDataKinds.Phone.p
}, null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
contactID = c.getString(2);
Bitmap photoBitmap = null;
Uri photo=null;
try {
photo = Uri.withAppendedPath(uri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageURI(photo);
// ImageView profile = (ImageView)findViewById(R.id.imageView1);
// Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contactID);
// InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri);
// BufferedInputStream buf = new BufferedInputStream(photo_stream);
// Bitmap my_btmp = BitmapFactory.decodeStream(buf);
// profile.setImageBitmap(my_btmp);
} catch (Exception e) {
e.printStackTrace();
}
// contactNumber = cursor.getString(cursor.getColumnIndex((ContactsContract.CommonDataKinds.Phone.NUMBER)));
showSelectedNumber(type, number,contactID,photo.toString());
}
// Bitmap photo = null;
//
// try {
//
// InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
// ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
//
//
//
// if (inputStream != null) {
// photo = BitmapFactory.decodeStream(inputStream);
// ImageView imageView = (ImageView) findViewById(R.id.imageView1);
// imageView.setImageBitmap(photo);
// }
//
// assert inputStream != null;
// inputStream.close();
//
// } catch (IOException e) {
// e.printStackTrace();
// }
}catch(Exception e){
Log.w(TAG,e+"");
} finally {
if (c != null) {
c.close();
}
}
}
}
} else {
Log.w(TAG, "Unknown Activity Result from add contact: "
+ resultCode);
}
}
}
in above code i have tried many things, like input stream etc. but still not getting photo of the contact but successful to get photo path.
When i am going to set data on image view it is not showing any thing on it.
If you already have the path, you could try this:
private void previewImage(String path) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5; // setting the photo quality
final Bitmap bitmap = BitmapFactory.decodeFile(path, options);
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
Retrieving thumbnail Image follow this code ..
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
Try out below code it will help you get contact number and its id and from that id number its will fetch the contact number.
public class DemoContact extends Activity {
private static final String TAG = DemoContact.class.getSimpleName();
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private Uri uriContact;
private String contactID, contactName; // contacts unique ID
private TextView m_contactName;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_contactName = (TextView) findViewById(R.id.textView1);
}
public void onClickSelectContact(View btnSelectContact) {
// using native contacts selection
// Intent.ACTION_PICK = Pick an item from the data, returning what was
// selected.
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI),
REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS
&& resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactNumber();
retrieveContactPhoto();
m_contactName.setText("Contact Name: "+contactName);
}
}
//Retrieve the Contact photo based on the contactId
private void retrieveContactPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts
.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.img_contact);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Get the contact number of the selected contact.
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[] { ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME }, null, null,
null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID
.getColumnIndex(ContactsContract.Contacts._ID));
contactName = cursorID.getString(cursorID .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = "
+ ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[] { contactID }, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone
.getString(cursorPhone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
}
OutPut:

Setting Ringtone to individual contact doesn't apply

As many people asked here ,I figured out the process of setting custom rings to specifc contacts by using the following link:
Setting contact custom ringtone, how?
I used #viperbone's solution and it helped me showing the user the contact picking window and getting the id of selected person.
Now the problem is: after all codes run ,the ringtone for contact chosen is still the same.
I searched many topic in here and googled it and they all do this process kind of using same method but mine just doesn't work.
here is the code:
public class SetCustomContacts extends Activity {
// put that constant in your class
static public final int CONTACT_CHOOSER_ACTIVITY_CODE = 73729;
private String musicId;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
musicId = getIntent().getExtras().getString("music_id");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_CHOOSER_ACTIVITY_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (CONTACT_CHOOSER_ACTIVITY_CODE) :
if (resultCode == Activity.RESULT_OK) {
try{
Scanner in = new Scanner(musicId).useDelimiter("[^0-9]+");
int integer = in.nextInt();
String filePath2 = getFilesDir() + File.separator + String.valueOf(integer) + ".mp3";
File ringFile = new File(filePath2);
File fileDest = null;
try{
fileDest = new File(Environment.getExternalStorageDirectory().getPath(), "ringSpecificContact" + ".mp3");
copy(ringFile, fileDest);
}catch (Exception ex){
Log.d("File Copy: ", ex.toString());
}
Uri contactData = data.getData();
String contactId = contactData.getLastPathSegment();
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
Cursor localCursor = getContentResolver().query(contactData, PROJECTION, null, null, null);
localCursor.moveToFirst();
String contactID = localCursor.getString(localCursor.getColumnIndexOrThrow("_id"));
String contactDisplayName = localCursor.getString(localCursor.getColumnIndexOrThrow("display_name"));
Uri localUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contactID);
localCursor.close();
ContentValues localContentValues = new ContentValues();
localContentValues.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
localContentValues.put(ContactsContract.Data.CUSTOM_RINGTONE, Environment.getExternalStorageDirectory() + "/ringSpecificContact.mp3");
getContentResolver().update(localUri, localContentValues, null, null);
Toast.makeText(this, contactDisplayName, Toast.LENGTH_LONG).show();
} catch(Exception ex){
Log.d("on onActivityResult: ", ex.toString());
}
}
break;
}
onBackPressed();
}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}

How to get path of image saved in gallery in android

I am making an android application that takes image from the camera and saves it in the gallery. What i want is to get path of the saved image. I have tried using intent.getData() but is not working..
I have tried using intent.getData() but is not working..
you Will get intent as NULL in Some Samsung Devices Like Samsung Galaxy S3 with Android OS Version 4.1.1.
i have face this Problems and Solve it by Below way you can try it out if it helps you.
While Calling intent for Image Capture :
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
mImageCaptureUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else {
new AlertDialog.Builder(BuildInukshk_4_Camera.this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState)
.setCancelable(true).create().show();
}
} else { // pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
Inside OnActivityResult Method :
case PICK_FROM_CAMERA:
Log.i("TAG", "Inside PICK_FROM_CAMERA");
// Final Code As Below
try {
Log.i("TAG", "inside Samsung Phones");
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select
// only
// mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
// At the moment, this is a bit of a hack, as I'm returning ALL
// images, and just taking the latest one. There is a better way
// to
// narrow this down I think with a WHERE clause which is
// currently
// the selection variable
Cursor myCursor = this.managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
// myCursor.close();
}
// Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID
+ " DESC";
myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
// This will actually give yo uthe file path location of the
// image.
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
mImageCaptureUri_samsung = Uri.fromFile(new File(
largeImagePath));
mImageCaptureUri = null;
} finally {
// myCursor.close();
}
// These are the two URI's you'll be interested in. They give
// you a
// handle to the actual images
Uri uriLargeImage = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the
// URI's
// to my own objects anyways...
} catch (Exception e) {
mImageCaptureUri_samsung = null;
Log.i("TAG",
"inside catch Samsung Phones exception " + e.toString());
}
try {
Log.i("TAG",
"URI Samsung:" + mImageCaptureUri_samsung.getPath());
} catch (Exception e) {
Log.i("TAG", "Excfeption inside Samsung URI :" + e.toString());
}
try {
Log.i("TAG", "URI Normal:" + mImageCaptureUri.getPath());
} catch (Exception e) {
Log.i("TAG", "Excfeption inside Normal URI :" + e.toString());
}
break;
After Running Below Code you Will get Two URIs mImageCaptureUri_samsung and mImageCaptureUri
you will get the mImageCaptureUri as your Path if you are running the App with Simple Devices and you will get your Cpatured Image path in mImageCaptureUri_samsung if you are running with Devices Like Samsung Galaxy S3.
Further you all can go ahead with your Code. it Works For me Very Fine With all the Devices i have tested on.
Also if Someone is having Problem with Above Code than they can reference the Below Great Link Solution of Samsung Galaxy S3
Hope it will Help.
try this one :
public class Camera extends Activity {
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TakePhoto();
}
public void TakePhoto()
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == CAMERA_REQUEST)
{
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
This is how I have done:
First create the image uri and with the intent ACTION_IMAGE_CAPTURE pass an extra MediaStore.EXTRA_OUTPUT with this value.
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
capturedImageURI = ImageUtils.takePicture(ReceiptFormActivity.this);
}
});
Then onActivityResult convert this uri path to String path and call the method which will fetch the bitmap from this string path and set it on your imageView.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONSTANTS.TAKE_PICTURE)
{
if (resultCode == RESULT_OK)
{
if(capturedImageURI != null)
{
Utils.imagePath = ImageUtils.getStringPathFromURI(ReceiptFormActivity.this, capturedImageURI);;
setThumbnail();
}
}
}
}
void setThumbnail()
{
try{
if(Utils.imagePath != null)
{
((TextView)findViewById(R.id.display_image)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File f = new File(Utils.imagePath);
if(f.exists())
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.fromFile(f);
intent.setDataAndType(imgUri, "image/*");
startActivityForResult(intent,2000);
}
}
});
File imgFilePath = new File(Utils.imagePath);
if(imgFilePath != null && imgFilePath.exists())
{
Bitmap bitmap = ImageUtils.decodeFile(imgFilePath, CONSTANTS.THUMBNAIL_HEIGHT, CONSTANTS.THUMBNAIL_WIDTH);
if(bitmap != null)
{
receipt_thumbnail.setImageBitmap(bitmap);
return;
}
}
}
}
catch (Exception e) {
receipt_thumbnail.setImageResource(R.drawable.some_img);
}
/*
* default img incase of not any exception and no bitmap either.
*/
receipt_thumbnail.setImageResource(R.drawable.some_img);
}
ImageUtils.java
public class ImageUtils {
public static Uri takePicture(Context context)
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Receipt_" + System.currentTimeMillis());
Uri mCapturedImageURI = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
((Activity) context).startActivityForResult(intentPicture,CONSTANTS.TAKE_PICTURE);
return mCapturedImageURI;
}
public static String getStringPathFromURI(Context context, Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
public static Bitmap decodeFile(File f, int thumbnailReqHeight, int thumbnailReqWidth)
{
Bitmap b = null;
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > thumbnailReqHeight || o.outWidth > thumbnailReqWidth)
{
scale = (int)Math.pow(2, (int) Math.round(Math.log(thumbnailReqHeight / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o);
fis.close();
} catch (IOException e) {
}
return b;
}
}
The code is very fine. Try giving permission of android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE in android manifest.

can not send mail with attachment in Android

i have a problem to send mail with attachment. I'm using Javamail libraries (mail.jar, activitation.jar and additional.jar ). I can send mail accurately. But i can not send mail with an attachment is image to mail. I choose an image from gallery, and it is addded as my filename
File f = new File("file://" + uri.getPath());
I think i have a problem when datasource took the my file's path. Whatever you can see much more thing in my code:(i've solved this problem and it is the last situation of my code)
first of all i add to view of my attachment :
Button Add = (Button) findViewById(R.id.btnAdd);
Add.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
onAddAttachment2("image/*");
}
});
here is my onAddAttachment2 and onActivityResult code
private void onAddAttachment2(final String mime_type) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(mime_type);
startActivityForResult(Intent.createChooser(i, null),
ACTIVITY_REQUEST_PICK_ATTACHMENT);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
mAttachments = (LinearLayout) findViewById(R.id.attachments);
switch (requestCode) {
case ACTIVITY_REQUEST_PICK_ATTACHMENT:
Uri _uri = imageReturnedIntent.getData();
addAttachment(_uri);
Cursor cursor = getContentResolver()
.query(_uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
String imageFilePath = cursor.getString(0);
uris.add(imageFilePath);
Log.v("imageFilePath", imageFilePath);
break;
}
}
As u see there is i have an AddAttachment method. Here is the code:
private void addAttachment(Uri uri) {
addAttachment(uri, null);
}
private void addAttachment(Uri uri, String contentType) {
long size = -1;
String name = null;
ContentResolver contentResolver = getContentResolver();
Cursor metadataCursor = contentResolver.query(uri, new String[] {
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null,
null, null);
if (metadataCursor != null) {
try {
if (metadataCursor.moveToFirst()) {
name = metadataCursor.getString(0);
size = metadataCursor.getInt(1);
}
} finally {
metadataCursor.close();
}
}
if (name == null) {
name = uri.getLastPathSegment();
}
String usableContentType = contentType;
if ((usableContentType == null)
|| (usableContentType.indexOf('*') != -1)) {
usableContentType = contentResolver.getType(uri);
}
if (usableContentType == null) {
usableContentType = getMimeTypeByExtension(name);
}
if (size <= 0) {
String uriString = uri.toString();
if (uriString.startsWith("file://")) {
Log.v(LOG_TAG, uriString.substring("file://".length()));
File f = new File(uriString.substring("file://".length()));
size = f.length();
} else {
Log.v(LOG_TAG, "Not a file: " + uriString);
}
} else {
Log.v(LOG_TAG, "old attachment.size: " + size);
}
Log.v(LOG_TAG, "new attachment.size: " + size);
Attachment attachment = new Attachment();
attachment.uri = uri;
attachment.contentType = usableContentType;
attachment.name = name;
attachment.size = size;
View view = getLayoutInflater().inflate(
R.layout.message_compose_attachment, mAttachments, false);
TextView nameView = (TextView) view.findViewById(R.id.attachment_name);
ImageButton delete = (ImageButton) view
.findViewById(R.id.attachment_delete);
nameView.setText(attachment.name);
delete.setTag(view);
view.setTag(attachment);
mAttachments.addView(view);
delete.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
uris.remove(view.getTag());
mAttachments.removeView((View) view.getTag());
}
});
}
and Attachment class that has properties
static class Attachment implements Serializable {
private static final long serialVersionUID = 3642382876618963734L;
public String name;
public String contentType;
public long size;
public Uri uri;
}
finally in my Mail.java class i have AddAttachment method:
public void addAttachment(String file) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file);
_multipart.addBodyPart(messageBodyPart);
}
When i clicked to send button, it have been sending to adress is written.
But my attachment can not be shown. I have no error when i sent mail. I hope you had a solution for these problem...
Edit: OK finally i've solved the problem!..
first i've defined ArrayList<String> uris = new ArrayList<String>();
Then i've used it in my onActivityResult method like that uris.add(imageFilePath);
lastly, before m.send code block i've add the images:
for (int i = 0; i<uris.size(); i++)
{
m.addAttachment(uris.get(i).toString());
}
in my Mail.java class, the changes shown like that :
public void addAttachment(String file) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file);
_multipart.addBodyPart(messageBodyPart);
}
There definitely the problem of MIME Type. If you want to image attached with email you can send this with simply using
private void sendEmail(String[] to,String[] cc,String subject, String message)
{
ArrayList<Uri> uris = new ArrayList<Uri>();
Uri u = Uri.fromFile(new File(front_image));
Uri u1 = Uri.fromFile(new File(side_image));
uris.add(u);
uris.add(u1);
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("image/jpg");
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
/*emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_right_latest_path));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_right_prev_path));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_front_latest_path));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_front_prev_path));*/
startActivity(Intent.createChooser(emailIntent, "Email"));
}
I hope the string you're passing to the addAttachment method is a file name, not a URL (i.e., doesn't start with "file:").
To debug your problem, add code to the addAttachment method that uses a FileInputStream and see if you can read the data in the file. If you can't, JavaMail won't be able to either.
Also, turn on Session debugging and examine the protocol trace to see what JavaMail is actually sending. That might provide more clues. Or, in your code that actually sends the message, add msg.writeTo(new FileOutputStream("msg.txt")) and see what's written to the file.

Categories

Resources