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"));
Related
My old code was only working well till lolipop. i tried to write a new one but its not working in marshmallow either. I been sitting on this for the last two days and i dont have a clue :(.
public void share(View view){
niv1 = (NetworkImageView) findViewById(R.id.imgNetwork);
File file = getLocalBitmapFile(niv1);
Uri bmpUrii = FileProvider.getUriForFile(this, "com.myfileprovider", file);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUrii);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "share");
shareIntent.putExtra(Intent.EXTRA_TEXT, Datas.Address);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
}
public File getLocalBitmapFile(NetworkImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
File bmpUri = null;
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
I am trying to attach image from my gridview to gmail or facebook,but whenever i tried to attach my app got crash,and i am getting following error with nullpointer exception,following is my code with gridview image selection,can any one help?
public class Free_Cover_Activity extends AppCompatActivity
{
GridView grid;
int[] imageId = {
R.drawable.discovercover,
R.drawable.burpresswordfree,
R.drawable.flyfree,
R.drawable.cantmovefree,
R.drawable.cantmovewordfree,
R.drawable.chalkthisfree,
R.drawable.fivehundredmetersfree,
R.drawable.freeexercise,
R.drawable.gym_smilie,
R.drawable.hundredcalrairesfree,
R.drawable.injuryfree,
R.drawable.jumpropefree,
R.drawable.nicesnathcfree,
R.drawable.personglrecordfree,
R.drawable.posefree,
R.drawable.pushupfree,
R.drawable.shoulder,
R.drawable.timewordfree,
R.drawable.unbrokernfree,
R.drawable.weightbeltfree
};
private Bitmap mBitmap;
private Intent email;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.free_cover_gridview);
android.support.v7.app.ActionBar abar = getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#D64365"));
abar.setBackgroundDrawable(colorDrawable);
abar.hide();
CustomGridFreeCover adapter =
new CustomGridFreeCover(Free_Cover_Activity.this, imageId);
grid=(GridView)findViewById(R.id.freecover_grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
try
{
Bitmap largeIcon =
BitmapFactory.decodeResource(getResources(), R.drawable.discovercover);
/*
replace "R.drawable.bubble_green" with the image resource
you want to share from drawable
*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
largeIcon.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f =
new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
//remember close de FileOutput
fo.close();
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
//set your subject
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hi");
//set your message
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "How are you");
String imagePath = Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg";
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
}
});
}
public class CustomGridFreeCover extends BaseAdapter
{
private Context mContext;
//private final String[] web;
private final int[] Imageid;
public CustomGridFreeCover(Context c,int[] Imageid )
{
mContext = c;
this.Imageid = Imageid;
//this.web = web;
}
#Override
public int getCount()
{
//TODO Auto-generated method stub
return Imageid.length;
}
#Override
public Object getItem(int position) {
//TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
//TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
//TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
grid = new View(mContext);
grid = inflater.inflate(R.layout.free_cover_griditem, null);
//TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image_freecover);
//textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
}
Here is the working code which you need:
Firstly save image from Drawable to SD Card here is the code:
try{
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.bubble_green);
//replace "R.drawable.bubble_green" with the image resource you want to share from drawable
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
largeIcon.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
f.createNewFile();
// write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then get the saved image from SD card and attach in the email intent like this:
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hi"); //set your subject
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "How are you"); //set your message
String imagePath = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
This is what worked for me perfectly.
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.share_subject));
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getResources().getString(R.string.share_message));
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://" + C.PROJECT_PATH + "/drawable/" + R.drawable.image_to_share);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
But I will always recommend to decode a Bitmap from this resource, save it as a File in the storage and then use that file. A more reliable way this directly using from the resources.
roman thing is you are passing a null bitmap object
Bitmap icon = mBitmap;
you need to assign bitmap first then the code will start work
for more info you can have a look on to below links :-
https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents
http://developer.android.com/training/sharing/send.html
First Convert your drwable to image and store it on SDCard
Store Drawable to SD card
Then
private void shareImage() {
Intent share = new Intent(Intent.ACTION_SEND);
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
// Make sure you put example png image named yourImg.png in your
// directory
String imagePath = Environment.getExternalStorageDirectory()
+ "/yourImg.png";
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image!"));
}
I want to share animated gif images that are in my drawable folder.
The code works so far, but the shared gif file is not animated. You can only see the first image of the animation. Does someone know how it could work?
Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
R.drawable.animated_gif);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/gif");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.PNG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file.gif");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f, true);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file:///sdcard/temporary_file.gif"));
startActivity(Intent.createChooser(share, "Share Image"));
Well, you are geting static bitmap from drawable. I recomend you to use GifDrawable in Glide library and this approach for sending animated gifs (in case you loaded your gif image into ImageView):
private Uri getLocalBitmapUri(ImageView imageView, String link) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
if (drawable instanceof GifDrawable) {
try {
// Store image to default external storage directory
String fileName = link.substring(link.lastIndexOf('/') + 1, link.length());
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "shared_gif_" + System.currentTimeMillis() + ".gif");
file.getParentFile().mkdirs();
GifDrawable gifDrawable = ((GifDrawable) imageView.getDrawable());
FileOutputStream out = new FileOutputStream(file);
out.write(gifDrawable.getData());
out.close();
return Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
...
Uri bmpUri = Utils.getLocalBitmapUri(gifImageView, post.media_content.get(0).file);
if (bmpUri != null) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/gif");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "title");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "text");
sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else {
// ...sharing failed, handle error
}
...
I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly
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.