I'm trying to share image with Intent.ACTION_SEND but getting this error:
cannot resolve method getResource()
This is the code I'm trying to share image with:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/myFolder");
dir.mkdirs(); // build directory
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fileName = "Image-"+ n +".jpg";
File file = new File(dir, fileName);
if (file.exists ()) file.delete ();
try {
FileOutputStream outStream = new FileOutputStream(file);
InputStream is;
Bitmap bitmap;
is = this.getResources().openRawResource(R.drawable.image1);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, outputFileUri);
startActivity(Intent.createChooser(intent, "Share this image via"));
If you are in a fragment use:
getActivity().getResources();
Or try:
getApplicationContext().getResources();
If you are in an Activity but in an inner class edit the word this in this line:
is = this.getResources().openRawResource(R.drawable.image1);
To:
is = Your_Activity_Class_Name.this.getResources().openRawResource(R.drawable.image1);
First, the method is called getResources(), with an 's'. It is a method of the base Context class. As such you have to access it from your Activity or Service. If your function belongs to a separate (non-Context) class you should either keep a reference to the context (bad practice) or use getResources() after your function has finished, in a callback, for example, in the context.
If its an fragment this is what fix the issue for me:
getActivity.getString(R.string.string_name);
But if its an activity you can use:
this.getString(R.string.string_name);
And finally in an Adapter you can do:
getContext().getResources().getString(R.string.string_name);
Related
I have followed a lot of guides of how to save and reload images to the phone and came to this:
In the videos it works but for some reason it does not work for me.
Is there maybe a better version of doing this? And how can I read from this later so I can paste it with Picasso into another ImageView?
(Update: Logcat is saying : Logcat says this: java.io.FileNotFoundException: /storage/emulated/0/LiFit/profileimage.jpg (No such file or directory) but I am clearly creating this folder wiht the mkdir command so why isn´t it workiing ?)
BitmapDrawable drawable = (BitmapDrawable) profilBild.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+ "/LiFit");
directory.mkdir();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(directory, fileName);
Toast.makeText(getActivity(), "Pic saved", Toast.LENGTH_LONG).show();
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
try {
outputStream.flush();
outputStream.close();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
getContext().sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Apparently you need to change the permissions in the app settings to....
I want to send image from my app via messenger. I was looking on Stack Overflow and I found answer which works for WhatsApp. When I tried to change "com.whatsapp" to "com.facebook.orca", it stops working. Here is my code:
public void shareImageMessenger() {
Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.koza);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file_1.jpg");
try {
f.createNewFile();
new FileOutputStream(f).write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"temporary_file_1.jpg"));
share.setPackage("com.facebook.orca");
startActivity(Intent.createChooser(share, "Share Image"));
}
After spending a lot of time on this:
Check if permissions are given. Then:
Step 1: Create ImageView of the image you want to in the activity and then convert it itno bitmap
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//save the image now:
saveImage(bitmap);
//share it
send();
Step 2: Store the image in internal folder:
private static void saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "Image-test" + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Step 3: Send the saved image:
public void send() {
try {
File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent, "Share using"));
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Now after sending you can delete the saved image if you don't want it in your storage. Check other link to do that.
Referring your linked post,You could modify the share intent.
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///assets/epic/adv.png"));
this.startActivity(Intent.createChooser(share, "share_via"));
The intent launches the apps which handles Intent.ACTION_SEND. If you want specific app to be respond, make sure you are aware of the package name and you need set package name share.setPackage("");
I have app and i am letting user to make screenshot and share it, all working fine just one problem..
When user for example make screenshot and press on Facebook icon > then he press cancel sharing ,next time when he want to do another share he will see the old screen shoot , how can make it take the last screenshot always??
** i have each image has different file name but the share always taking the last action that didn't finish.
(if user do share all will work fine ,next screen shoot will be the new one )
here is my code
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() ,
"SCREEN"
+ System.currentTimeMillis() + ".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
uri =Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "جرب تطبيق نكت عراقية مضحكة الان!";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "تطبيق نكت
عراقية مضحكة");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "مشاركة بواسطة"));
}
You can do something like this.Remove the System.currentTimeMillis() from the name of your image so, that you do not have multiple copies of screenshots.So when you upload the image it always have the fresh screenshots.Now when you capture another screenshot you have to check is file exist if exist then delete it.
public void saveBitmap(Bitmap bitmap)
{
File file = new File(Environment.getExternalStorageDirectory(), "SCREEN.png");
if (file.exists()) {
file.delete();
}
imagePath = new File(Environment.getExternalStorageDirectory() , "SCREEN.png");
FileOutputStream fos;
try
{
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (IOException e)
{
Log.e("GREC", e.getMessage(), e);
}
}
So I take a screenshot of my activity, then save it to "screenshot.png". When trying to share it via, let's say, Whatsapp, I get an error: "could not send image". Same with gmail, pushbullet and basically all other apps. Therefore, I conclude that the file somehow exists, but it is either empty, or messed up... I don't know, honestly.
Here's the code:
Taking the activity screenshot:
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
Saving the screenshot:
public void saveBitmap(Bitmap bitmap) {
FileOutputStream fos;
String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
File f = new File(filePath);
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
And finally, the sharing itself:
if (id == R.id.action_share){
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("screenshot.png"));
startActivity(Intent.createChooser(share, "Teilen via"));
}
Where is my error? I don't get any errors in logcat, but I am unable to share the "screenshot".
Firstly, you should use :
share.putExtra(Intent.EXTRA_STREAM. Uri.fromFile(new File(getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png"));
But you would then get "Permission denied for the attachment" and you possibly would try but with no luck :(
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
So probably the best way to deal with this issue is to store the captured screenshot in media library and send the file from there.
public void share() {
String filePath=getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
String path;
try {
path = Images.Media.insertImage(getContentResolver(), filePath, "title", null);
Uri screenshotUri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(share, "Teilen via"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Hope it would help!
maybe an easy question: I want to share a bitmap I received over the net to twitter/facebook/etc with the default share "intent".
The code I found
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("image/jpeg");
sendIntent.putExtra(Intent.EXTRA_STREAM, "IDONTKNOW");
sendIntent.putExtra(Intent.EXTRA_TEXT,
"See my captured picture - wow :)");
startActivity(Intent.createChooser(sendIntent, "share"));
needs to be filled at the point "IDONTKNOW" with the bitmap. (this.bitmap)
I found no way to handle this without saving the bitmap to internal sd..
regards
Simply, you can convert a bitmap into PNG from external storage.
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = new File(path, getCurrentTime()+ ".png");
FileOutputStream fileOutPutStream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutPutStream);
fileOutPutStream.flush();
fileOutPutStream.close();
Then, you can get a URI through Uri.parse:
return Uri.parse("file://" + imageFile.getAbsolutePath());
Might be a little late now, but you could also do String url = Images.Media.insertImage(context.getContentResolver(), image, "title", null); if you don't care how it's stored.
Ok I got it on my own, it seems there is no way to get the image uri without saving the bitmap to disk, therefore I use this simple method:
private Uri storeImage() {
this.storedImage = null;
this.storeImage = true;
// Wait for the image
while (this.storedImage == null && !this.stop)
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.storeImage = false;
FileOutputStream fileOutputStream = null;
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, "cwth_" + getCurrentTime()+ ".jpg");
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
this.storedImage.compress(CompressFormat.JPEG, JPEG_STORE_QUALITY, bos);
try {
bos.flush();
bos.close();
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return Uri.parse("file://" + file.getAbsolutePath());
}
Send Binary Content
Binary data is shared using the ACTION_SEND action combined with setting the appropriate MIME type and placing the URI to the data in an extra named EXTRA_STREAM. This is commonly used to share an image but can be used to share any type of binary content:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
source http://developer.android.com/training/sharing/send.html