I did not manage to get a picture from activity to another activity.
this is my part of the code:
this is one activity:
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText website = ((EditText) findViewById(R.id.editText));
String g = website.getText().toString();
Intent intent = new Intent(CoohseImage.this, MainActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("image", bs.toByteArray());
intent.putExtra("message", g);
startActivity(intent);
}});
And this is the second activity:
targetImage = (ImageView) findViewById(R.id.targetimage);
Intent intent = getIntent();
message = intent.getStringExtra("message");
// b = intent.getByteExtra("image", "dfdd");
((TextView)findViewById(R.id.textView)).setText(message);
if(getIntent().hasExtra("image")) {
ImageView targetImage = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(getIntent().getByteArrayExtra("image"), 0, getIntent().getByteArrayExtra("image").length);
targetImage.setImageBitmap(b);
}
A better approach would be to just share the source of your bitmap between the Activities and load the bitmap in onCreate() of the newly created Activity.
This is not recommended because it costs a lot of memory.
in first Activity
Intent i = new Intent(this, second.class);
i.putExtra("data", bitmap)
startActivity(i);
in Second Activity
Bundle b = getIntent().getExtras();
Bitmap bmp = b.getParcelable("data");
I recommed to you saving the image to disk and open it in the second activity!
1-First you need to save bitmap in a file.
2-To get bitmap from image view:
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
3-To save it in a file:
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
4- Instead of sharing sending bitmap, send outputFileUri with intent to next activity.
5-Retrieve Image from outputFileUri to image view in second activity:
Uri uri = Uri.fromFile(outputFileUri );
imageView.setImageURI(uri);
Simply pass the reference to the object
int image = R.drawable.imageinquestion;
Intent i = new Intent(Act1.this, Act2.class);
i.putExtra("IMAGE", image);
startActivity(i);
In Act2
Bundle b = getIntent().getExtras();
if(b!=null)
{
image = b.get("IMAGE");//or getInt() or getString()
}
If its a website, send the link as a String
You have a limit of data you can send via Intent using bundle, so i strongly recommend you do as Elenasys: Save in disk and open in the target activity.(You can use the intent to send the path).
Related
Activity1.class
public class CategoryActivity extends BaseActivity implements View.OnClickListener {
private RelativeLayout mReLayout;
private byte[] mImageByte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
addControl();
addEventOnClick();
mReLayout.setDrawingCacheEnabled(true);
}
private void addEventOnClick() {
findViewById(R.id.layout_category_1).setOnClickListener(this);
}
private void addControl() {
mReLayout = (RelativeLayout) findViewById(R.id.relative_category);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.layout_category_1:
startActivity();
break;
default:
break;
}
}
private void startActivity() {
Bitmap layoutBitmap = Bitmap.createBitmap(mReLayout.getWidth(), mReLayout.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(layoutBitmap);
mReLayout.draw(canvas);
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
layoutBitmap.compress(Bitmap.CompressFormat.PNG, 90, bStream);
mImageByte = bStream.toByteArray();
Intent mIntent = new Intent(Activity1.this, Activity2.class);
mIntent.putExtra(Constant.BYTE_IMAGE, mImageByte);
startActivity(mIntent);
}
}
Activity2.class
OnCreate
byte[] mImageByte=getIntent().getExtras().getByteArray(Constant.BYTE_IMAGE);
Bitmap bmp = BitmapFactory.decodeByteArray(mImageByte, 0, mImageByte.length);
mImageView.setImageBitmap(bmp);
When I click onClickListener. It show bug : FAILED BINDER TRANSACTION !!!
Please. Help me!
I think the reason is you're trying to put a Bitmap as an Intent extra. Although it's theoretically possible, I think the size of the Image limits such possibilities.
If you want to pass an image to another activity, then first
Save the Bitmap to a file
Send the filepath as a String to the next activity
Use the filepath from the next activity to recreate the Bitmap
If that is difficult, then try using a Singleton to store a Bitmap temporarily in memory.
Here's how to save it to disk.
First add the permission in the manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then...
File file = new File(Environment.getExternalStorageDirectory() + "imageBitmap" + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Now send the filename to the next activity.
mIntent.putExtra("filename", "imageBitmap");
On the next activity, recreate the bitmap.
String fName = getIntent().getStringExtra("filename");
String path = Environment.getExternalStorageDirectory() + fName + ".png"
Bitmap bm = BitmapFactory.decodeFile(path);
Hope this helps.
i want to pass an image from one activity to another, this is my code:
public boolean launchCamera(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) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(MainActivity.this, "Please check SD card! Image shot is impossible!", Toast.LENGTH_LONG);
return false;
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
//start camera intent
this.startActivityForResult(intent, MenuShootImage);
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.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
public Bitmap grabImage()
{
this.getContentResolver().notifyChange(mImageUri, null);
ContentResolver cr = this.getContentResolver();
Bitmap bitmap=null;
try
{
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Failed to load", e);
}
return bitmap;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Intent imagepass = null;
Bitmap bitmap = null;
if(requestCode == MenuShootImage && resultCode == RESULT_OK)
{
bitmap = this.grabImage();
imagepass = new Intent(this,MainActivity2.class);
imagepass.putExtra("imagepass", bitmap );
startActivity(imagepass);
}
}
the problem is that i cant reach to the other activity at all, in debug mode i get to the line startactivity(imagepass); and dont go to the MainActivity2.
can somebody help me?
First of all, if you really want to pass your bitmap through Intent, you need to convert it to Byte Array first since Bitmap couldn't be attached with Intent like that.
Here is how to do that https://stackoverflow.com/a/11010565/4651112
But according to the best practices, I suggest you NOT TO SEND A BITMAP THROUGH INTENT AT ALL. Send a filename image and let the target Activity decode it from file. It's much better.
1) First Convert Image into Byte Array and then pass into Intent and in next activity get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView.
Convert Bitmap to Byte Array:-
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Pass byte array into intent:-
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
Get Byte Array from Bundle and Convert into Bitmap Image:-
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
2) First Save image into SDCard and in next activity set this image into ImageView.
3) Pass Bitmap into Intent and get bitmap in next activity from bundle, but the problem is if your Bitmap/Image size is big at that time the image is not load in next activity
I have my full screen activity:
public class FullImageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
BitmapDrawable bm = (BitmapDrawable) imageView.getDrawable();
Bitmap mysharebmp = bm.getBitmap();
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mysharebmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//you can create a new file name "test.jpeg"
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + "test.jpeg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Log.d("done","done");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "test.jpeg";
Uri m = Uri.parse(path);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, m);
startActivity(Intent.createChooser(sharingIntent,
"Share image using"));
}
}
Why is whatsapp the only app what is working?
All other apps are telling that they are failed or unable to download....
I would like to share with every app and i don´t know what i´m doing wrong plz help me i bet it´s easy for you.
Thx dudes!
Closed
Found the solution
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///mnt/sdcard/Pictures/tmp.jpeg"));
I am learning android and working on an application to takes pictures and send them through email. I have got the picture in ImageView in the code below, but am not sure how to send this picture as an email attachment, without saving the picture to file on the device.
Ideally i would like to know if that is possible? If yes can you point me the correct direction on how to implement the same. Also(optionally) if the picture can be compressed.
public class EmailPic extends Activity implements OnClickListener{
ImageButton ibEmail;
Button bEmail;
ImageView ivEmail;
Intent intentEmail;
Bitmap bmpEmail;
final static int picData = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pic_email);
initializeVars();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmpEmail = BitmapFactory.decodeStream(is);
}
private void initializeVars() {
ibEmail = (ImageButton)findViewById(R.id.ibTakePicEmail) ;
ivEmail = (ImageView)findViewById(R.id.ivPicEmail);
bEmail = (Button) findViewById(R.id.bSendPicEmail);
bEmail.setOnClickListener(this);
ibEmail.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibTakePicEmail:
intentEmail = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentEmail,picData);
break;
case R.id.bSendPicEmail:
String message = "email Body";
String[] recipients = new String[]{"mymail.com"};
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,message);
startActivity(emailIntent);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Bundle ext = data.getExtras();
bmpEmail = (Bitmap)ext.get("data");
//Log.d("StatusActivity","bmpEmail >>"+bmpEmail);
ivEmail.setImageBitmap(bmpEmail);
}
}
}
Try out as below:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.parse("android.resource://your package name/"+R.drawable.ic_launcher);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL,recipients);
shareIntent.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(shareIntent, "Send your image"));
EDITED:
Declare the File variable
File pic;
In your OnActivityResult() apply changes as below:
Bundle ext = data.getExtras();
bmpEmail = (Bitmap)ext.get("data");
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
bmpEmail.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
And in your send email code add the line
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
So, You want to capture the image from the ImageView, compress it and then attach.
Basically the process is :
Get the Image from the ImageView.
Convert to Bitmap.
Save it.(You have to do it in any case, if you want to attach it)
Hopefully you can delete it afterwards.
Attach to email Intent.
First of all get the cached bitmap of the ImageView
Bitmap myBitmap = yourImageView.getDrawingCache();
This will return the cached bitmap from the ImageView.
Compress it and save
URI FILENAME; //URI For the ImageView, we need earlier to send
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
myBitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
fos.close();
Create your Send Intent
String message = "email Body";
String[] recipients = new String[]{"mymail.com"};
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,message);
emailIntent.putExtra(Intent.EXTRA_STREAM, FILENAME); //this line is added to your code
startActivity(emailIntent);
You can delete the image afterward if you need to.
I have following method to Capture Screen on Action Item Click. Its working on Android <2.3 but not on 4+. What is wrong with this way of screen capture.
private void captureScreen() {
View v = mapView.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap capturedBitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
if(capturedBitmap != null) {
Intent intent = new Intent(this, ScreenCapturedAlertActivity.class);
intent.putExtra("capturedImage", capturedBitmap);
intent.putExtra("name", location.getName());
startActivity(intent);
} else {
Toast.makeText(this, "Screen Capture Failed", Toast.LENGTH_SHORT).show();
}
}
The ScreenCaputureAlertActivity.java >>>
public class ScreenCapturedAlertActivity extends SherlockActivity {
private ImageView capturedImage;
private Bitmap capturedBitmap;
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_screencaptured_alert);
capturedBitmap = (Bitmap) getIntent().getParcelableExtra("capturedImage");
name = getIntent().getStringExtra("name");
capturedImage = (ImageView) findViewById(R.id.ivCapturedImage);
capturedImage.setImageBitmap(capturedBitmap);
}
private void saveAndShare(boolean share) {
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/capture/");
if(!dir.exists())
dir.mkdirs();
FileOutputStream outStream = null;
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
File file = new File(dir, "Capture "+n+".jpg");
if(file.exists()) {
file.delete();
}
try {
outStream = new FileOutputStream(file);
capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
}
if(share) {
Uri screenshotUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.putExtra(Intent.EXTRA_SUBJECT, "Location of " + name);
intent.putExtra(Intent.EXTRA_TITLE, getText(R.string.screen_share_message));
intent.putExtra(Intent.EXTRA_TEXT, getText(R.string.screen_share_message));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share with"));
finish();
} else {
Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory())));
finish();
}
}
public void saveCapture(View view) {
saveAndShare(false);
}
public void shareCapture(View view) {
saveAndShare(true);
}
}
Thanks to #KumarBibek guidance.
The error I was getting was
!!! FAILED BINDER TRANSACTION !!!
So as from the selected answer from the link
Send Bitmap as Byte Array
I did like this in first activity:
private void captureScreen() {
View v = mapView.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap capturedBitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
capturedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
if(capturedBitmap != null) {
Intent intent = new Intent(this, ScreenCapturedAlertActivity.class);
intent.putExtra("capture", byteArray);
intent.putExtra("name", location.getName());
startActivity(intent);
} else {
Toast.makeText(this, "Screen Capture Failed", Toast.LENGTH_SHORT).show();
}
}
And in ScreenCapturedAlertActivity :
byte[] byteArray = getIntent().getByteArrayExtra("capture");
capturedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
It is working WELL now. Thanks again to #KumarBibek
Instead of passing the whole bitmap, try passing the file saved file's path to the next activity. Bitmap is a large object, and it's not supposed to be passed around like that.
Since you already checked the the image is being saved fine, if you deal with paths instead of bitmaps, I think it would solve your problem.