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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With