Android Send only 1 image via email in app - android

I have created a "Contact Us" page on my app and the idea is you have the option to send a picture to an already predetermind email address. The problem I have is its taking all the images from the gallery of the phone and sending them all in the email. All I want to do is send one picture. I cant seem to work out what to change to be able to just send one image. Is there anyone who could help?
Here is my code:
public class EmailActivity extends Activity {
Button send;
EditText address, subject, emailtext;
protected static final int CAMERA_PIC_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
send=(Button) findViewById(R.id.emailsendbutton);
address=(EditText) findViewById(R.id.emailaddress);
subject=(EditText) findViewById(R.id.emailsubject);
emailtext=(EditText) findViewById(R.id.emailtext);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if
(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
}
File pngDir = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.random.jbrefurb/quote");
if (!pngDir.exists())
pngDir.mkdirs();
Uri pngUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "random#yahoo.co.uk"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);
emailIntent.setType("image/jpeg");
EmailActivity.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
});
Button back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// fire intent
finish(); // finish current activity
Intent austinIntent = new Intent(view.getContext(),
ContactActivity.class);
startActivityForResult(austinIntent, 0);
}
});
Button camera = (Button) findViewById(R.id.button2);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== 0 && resultCode == Activity.RESULT_OK){
Bitmap x = (Bitmap) data.getExtras().get("data");
((ImageView)findViewById(R.id.imageView1)).setImageBitmap(x);
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
x.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (FileNotFoundException e) {
//
}catch (IOException e){
//
}
} }
}
Many thanks in advance

this is code i used in my application try if you need help..
private OnClickListener shareemail=new OnClickListener(){
#Override
public void onClick(View v) {
String address = "your emailaddress";
File filee;
if(address.length()==0)
{
AlertDialog.Builder ab=new AlertDialog.Builder(null);
ab.setMessage("Email Address must not be empty!");
ab.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.show();
}
else
{
ArrayList<Uri> uris = new ArrayList<Uri>();
Uri u;
Intent emailSession = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailSession.putExtra(Intent.EXTRA_SUBJECT,"your subject");
emailSession.setType("images/*");
emailSession.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {address});
emailSession.putExtra(android.content.Intent.EXTRA_TEXT,"body text");
FileWriter fw;
BufferedWriter bw;
try{
filee = new File(path of image you want to send);
if(filee.exists())
{
Uri u1 = Uri.fromFile(filee);
uris.add(u1);
emailSession.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailSession);
}
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}}
};

Related

email attachment is blank when using android intent

I need to send an attachment along with some basic information by mail using my app. But the attachment is blank when I'm trying to invoke the mail activity using intent.
Here's the code for getting filepath and then sending the attachment
public class Pickafile extends AppCompatActivity {
TextView textFile;
static String FilePath;
private static final int PICKFILE_RESULT_CODE = 1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Button buttonPick = (Button) findViewById(R.id.buttonpick);
Button bp = (Button) findViewById(R.id.proceed);
textFile = (TextView) findViewById(R.id.textfile);
buttonPick.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
});
bp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
//intent.setType("text/plain");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_SUBJECT, " Report Particulars for " + MainActivity.name);
/*File root = Environment.getExternalStorageDirectory();
File file = new File(root, FilePath);
if (!file.exists() || !file.canRead()) {
return;
}*/
/*if(FilePath!=null)
{
intent.putExtra(Intent.EXTRA_STREAM, FilePath);
}*/
intent.putExtra(Intent.EXTRA_TEXT, MainActivity.testfunc());
intent.putExtra(Intent.EXTRA_STREAM, FilePath);
//startActivity(Intent.createChooser(intent, "Pick an Email provider"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
FilePath = data.getData().getPath();
textFile.setText(FilePath);
}
break;
}
}
}
testfunc() is used to get body of the mail (name, age, phone,etc.)
Thanks in advance!
You should check the log if there is any error.
Possible case:
1. The file is too large, exceed maximum size of email attachment (20Mb for Gmail)
2. Missing READ_EXTERNAL_STORAGE permission if the file is saved in external storage.
3. Missing file_provider in manifest

Return to MainActivity from another activity with error message

I am a bit new in android and I want to return to main activity from current activity with error message in dialog box.
I have written a script which make a call to rest api and if there is no data or error from response then i want to return to main activity with that error in dialog box.
Here is what i am doing
txtScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
private void selectImage(){
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
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);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from 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 == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
byte[] b;
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = File.separator + System.currentTimeMillis() + ".jpg";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
System.out.println(filePath);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
/*FileInputStream fis = null;
try{
fis = new FileInputStream(filePath);
}catch (FileNotFoundException e){
e.printStackTrace();
}*/
b = bytes.toByteArray();
encode_string = Base64.encodeToString(b, Base64.DEFAULT);
System.out.println(b);
System.out.println(encode_string);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
obj = new JSONObject();
obj.put("image",encode_string);
obj.put("api_key",API_SECRET);
System.out.println(obj.toString());
}catch (Throwable t){
t.printStackTrace();
}
new Image().execute();
//new LongRunningGetIO().execute();
//ivImage.setImageBitmap(thumbnail);
}
This function is In Image class
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
//here i want to return to main activity with error
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}
Any idea thanks in advance
use startActivityForResults for passing value from current activity to previous activity
call Activity
Intent intent=new Intent(MainActivity.this,CurrentActivity.class);
startActivityForResult(intent, 2);
Handle result on MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String error=data.getStringExtra("MESSAGE");
//display error
}
}
Async
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
Intent intent=new Intent();
intent.putExtra("Error",message);
setResult(2,intent);
finish();
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}

Barcode Scanner in Fragment

I'm trying to insert a barcode scanner in my ListFragment and use this tutorial: BarcodeScanner
But if I click on of the two buttons (QR or barcode-scan), it seems that my app doesn't find the downloaded XZing Barcode Scanner. But it is installed! I don't get an issue :-( ...
I think something is wrong in the try-part
Here is the code of my ListFragment:
private Button b1;
private Button b2;
static final String ACTION_SCAN = "com.google.xzing.client.android.SCAN";
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getView().findViewById(R.id.button_scan_barcode_ean);
b2 = (Button) getView().findViewById(R.id.button_scan_qr_code);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR(v);
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBar(v);
}
});
}
public void scanBar(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
public void scanQR(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
private static AlertDialog showDialog(final Activity act, CharSequence title,
CharSequence message,
CharSequence buttonYes,
CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == 0){
if (resultCode == Activity.RESULT_OK){
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(getActivity(), "Content:" + contents + "Format" + format, Toast.LENGTH_LONG);
toast.show();
final EditText editTextBarcode = (EditText) getView().findViewById(R.id.editText_barcode);
editTextBarcode.setText(contents);
}
}
}
Any ideas?
There is a typo in your ACTION_SCAN String. You wrote "xzing" instead of "zxing".
The correct String is
"com.google.zxing.client.android.SCAN"

Unable to set image on Image view after uploading finish

public class FragProfile extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = inflater.inflate(R.layout.frag_profile, container, false);
Profile_image = (ImageView) root.findViewById(R.id.frag_imgProfile);
texusername = (TextView) root.findViewById(R.id.textView);
editbutton = (ImageView) root.findViewById(R.id.imageView1);
textcityname = (TextView) root.findViewById(R.id.textView1);
// ((HomeActivity) getActivity()).notifcationbadge
// .setVisibility(View.GONE);
// ((HomeActivity) getActivity()).badgeicon.setVisibility(View.GONE);
// ((HomeActivity) getActivity()).EditProfileimage
// .setVisibility(View.VISIBLE);
((HomeActivity) getActivity()).posttext.setVisibility(View.GONE);
editbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent editnameandcity = new Intent(getActivity(),
EditnameandCity.class);
startActivity(editnameandcity);
}
});
SharedPreferences preferences = getActivity().getSharedPreferences(
AppConstants.LOGIN_PREFS, Context.MODE_PRIVATE);
member_id = preferences.getString("Member_id", "");
// member_id = "409";
image_Url = "http://api.lociiapp.com/TransientStorage/" + member_id
+ ".jpg";
Profile_image.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.select_dialog_item,
items);
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from
// camera
if (item == 0) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(
Environment
.getExternalStorageDirectory(),
"tmp_avatar_"
+ String.valueOf(System
.currentTimeMillis())
+ ".jpg"));
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent,
PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { // pick from file
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"),
PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
return root;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr,
Base64.DEFAULT);
new Uploadimage().execute(image_str);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists())
f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager()
.queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(getActivity(), "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 50);
intent.putExtra("outputY", 50);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager()
.getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager()
.getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getActivity().getContentResolver().delete(
mImageCaptureUri, null, null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
#Override
public void onResume() {
super.onResume();
new username().execute();
// MtDrawableManager.getInstance().fetchBitmapOnThread(image_Url,
// Profile_image);
AQuery aq = new AQuery(context);
aq.id(Profile_image).image(image_Url, true, false, 0,
R.drawable.imge);
}
class Uploadimage extends AsyncTask<String, Void, Void> {
InputStream inputStream;
private static final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Updating...");
pDialog.setMessage("Please wait...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
try {
String Url = Uri.encode(
"http://api.lociiapp.com/api/registration/ProfilePictureSaved?imageFile="
+ params[0] + "&member_id=" + member_id
+ "&picture_path=" + member_id + ".jpg",
ALLOWED_URI_CHARS);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(Url);
httppost.setHeader(
"Accept",
"text/html,application/xhtml+xml,application/xml,application/json;q=0.9,/;q=0.8");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println("15aug " + result);
} catch (Exception e) {
pDialog.dismiss();
pDialog.cancel();
System.out.println("Error in http connection " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
pDialog.cancel();
// MtDrawableManager.getInstance().fetchBitmapOnThread(image_Url,
// Profile_image);
AQuery aq = new AQuery(context);
aq.id(Profile_image).image(image_Url, true, false, 0,
R.drawable.imge);
Log.e("Image Url**************", image_Url);
}
}
this is my code fro Uploading image to server Using camera and gallery . i am able to Upload image in both case successfully but there is Profile_image is image view where i have print that image after uploading to server i am getting image_url correctly in postexcute method but its displaying image on image view Profile_image please tell me where amd doing i am able to find issue even in on resume method i have putted same code for display image .
You can try image load through image loader.
Download image loader through below link.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

How to attach an image from an app to gmail

The app has 2 buttons on the screen, 1 for taking a photo and attaching it on the screen and the second to attach the photo on gmail & send it to someone. I'm using this code for the second button
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", "test#gmail.com", null));
intent.putExtra(Intent.EXTRA_SUBJECT, "test");
intent.putExtra(Intent.EXTRA_TEXT, "text");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
But it doesn't attach the photo on gmail. It might be wrong. Here's the rest of the code.
public class MainActivity extends Activity {
private static int TAKE_PICTURE = 1;
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendbutton = (Button) findViewById(R.id.sendbutton);
sendbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", "test#gmail.com", null));
intent.putExtra(Intent.EXTRA_SUBJECT, "test");
intent.putExtra(Intent.EXTRA_TEXT, "text");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent,
"Choose an Email client :"));
}
});
Button cameraButton = (Button) findViewById(R.id.button_camera);
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
takePhoto(v);
}
};
public void takePhoto(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.image_view_camera);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "failed to load",
Toast.LENGTH_LONG).show();
}
}
}
}
}
Try this
You can see more at this link: Sharing content in android using action send intent
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "test");
sharingIntent.putExtra(Intent.EXTRA_TEXT, "text");
sharingIntent.putExtra(Intent.EXTRA_STREAM, targetUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}

Categories

Resources