I have tried everything but Image is not showing in Gallery, but its
saved in Internal Storage. I have tried several tutorials, but unable
to solve it .How can I implement it so that it is shown in Gallery
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(FullScreenActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//to get the image from the ImageView (say iv)
BitmapDrawable draw = (BitmapDrawable) fullscreenimage.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/IslamicStatusPics");
Log.e("DIR", String.valueOf(dir));
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(FullScreenActivity.this).create();
alertDialog.setTitle("Success");
alertDialog.setMessage("Image Saved to IslamicStatusPics Folder Successfully !");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/storage/emulated/0/IslamicStatusPics/"))));
// Toast.makeText(getApplicationContext(), "Image Saved to IslamicStatusPics Successfully !", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
// intent.setData(Uri.fromFile(dir));
// sendBroadcast(intent);
}else {
requestStoragePermission();
}
Please help me Guide in the Right Path. Thanks
You can try below code with saved file uri:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(outFile)); //change here
activity.sendBroadcast(mediaScanIntent);
} else {
activity.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
Related
This is my wallpapers downloading code. It works on only Google Photo. Please give me the simplest code to single click download the wallpapers.
How to download wallpaper in one click into gallery automatically?
private void downloadWallpaper(final Wallpaper wallpaper) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(wallpaper.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = saveWallpaperAndGetUri(resource, wallpaper.id);
if (uri != null) {
intent.setDataAndType(uri, "image/*");
mCtx.startActivity(Intent.createChooser(intent, "Islamic Writes"));
}
}
}
);
}
private Uri saveWallpaperAndGetUri(Bitmap bitmap, String id) {
if (ContextCompat.checkSelfPermission(mCtx, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat
.shouldShowRequestPermissionRationale((Activity) mCtx, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Intent intent = new Intent();
intent.setAction( Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", mCtx.getPackageName(), null);
intent.setData(uri);
mCtx.startActivity(intent);
} else {
ActivityCompat.requestPermissions((Activity) mCtx, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
return null;
}
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/Download");
folder.mkdirs();
File file = new File(folder, id + ".jpg");
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Intent intent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE );
mCtx.sendBroadcast(intent);
return FileProvider.getUriForFile( mCtx, BuildConfig.APPLICATION_ID +".provider",file );
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I want to capture image using camera and send it as attachment in Email.
I tried everything on Internet nothing is working for me. If anyone could help with code please.
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
File file = savebitmap(thumbnail);
sendMail(file);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "abcd" + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "abcd" + ".jpg");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
void sendMail(File mFile){
Uri uri = null;
uri = Uri.fromFile(mFile);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"abc#gmail.com"});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share!"));
}
}
Saving the bitmap:
{
.....
File file = savebitmap(thumbnail);
sendMail(file);
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalFilesDir().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, temp + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, temp + ".jpg");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
//and then
void sendMail(File mFile){
Uri uri = null;
uri = Uri.fromFile(mFile);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {""});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, EMAIL_SUBJECT);
intent.putExtra(android.content.Intent.EXTRA_TEXT, EMAIL_BODY);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share!"));
}
Here is an example from internet
https://androidexample.com/Camera_Photo_Capture_And_Show_Captured_Photo_On_Activity_/index.php?view=article_discription&aid=77&aaid=101
I am assuming you may not handle permission just like above link
when you run your app in 6.0 above like marshmallow device then need permission other wise no need to permission. that time your code work..
if run marshmallow device that time need permission then make below code ..
private void alertDialog(){
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getApplicationContext(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
then above method put in permission code like below ..
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
add two permission into manifest file ..
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
your error main problem is permission if you add this below line is work.
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
I am using this code to share an image:
File file = ImageLoader.getInstance().getDiskCache().get(imageUrl);
if (file != null && file.exists()) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(Intent.createChooser(intent, "Send"));
} else {
Toast.makeText(context, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
I used UIL to load the image previously, so mageLoader.getInstance().getDiskCache().get(imageUrl); returns the image file from disk cache.
Gmail, Hangouts, Messages, Drive etc can grab the file but on Google+, the grabbed is not gotten while Whatsapp says "This format is not supported". However if I save the file to Downloads folder and share via Gallery app, the same image is picked by both Google+ and Whatsapp.
You can try to save the file to the external cache, it's working for me. Example with Glide:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/*");
Glide.with(getContext())
.load("http://...url.here...")
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
try {
File file = new File(getContext().getExternalCacheDir(), "file_to_share.png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(Intent.createChooser(sendIntent, ""));
} catch (IOException e) {
Log.e("Share", e.getMessage(), e);
} finally {
}
}
});
In case you're using Universal Image Loader, I applied the accepted answer to save the image and delete it as soon as the user returns from sharing:
private File saveImage(String imageUri, String fileName) {
File file = new File(this.getExternalCacheDir(), fileName);
InputStream sourceStream = null;
File cachedImage = ImageLoader.getInstance().getDiskCache().get(imageUri);
if (cachedImage != null && cachedImage.exists()) {
Log.d(TAG, "Cache exists");
try {
sourceStream = new FileInputStream(cachedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Cache doesn't exist");
}
if (sourceStream != null) {
Log.d(TAG, "SourceStream is not null");
try {
OutputStream targetStram = new FileOutputStream(file);
try {
try {
IoUtils.copyStream(sourceStream, targetStram, null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
targetStram.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.d(TAG, "SourceStream is null");
Toast.makeText(this, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
return file;
}
private void shareImage(String imageUrl, String fileName) {
if (isSDReadableWritable()) {
file = saveImage(imageUrl, fileName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(Intent.createChooser(intent, "Send"), 20);
} else {
Toast.makeText(this, "Storage cannot be accessed", Toast.LENGTH_SHORT).show();
}
}
To delete the file just override onActivityResult and it'll be deleted immediately after sharing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20 && file != null) {
boolean isDelete = file.delete();
Log.d(TAG, "isDelete is " + isDelete);
}
}
Everytime the image is captured the folder creation section works fine but the image is not added to the folder
photoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode != RESULT_CANCELED)
{
folder = new File(Environment.getExternalStorageDirectory() + File.separator+"folder/");
if(!folder.exists())
{
folder.mkdirs();
Log.d("SDcard", "Folder created");
}
else
{
Log.d("SDCard", "Folder already exists");
}
File file = new File(Environment.getExternalStorageDirectory() + File.separator +"folder/");
Uri photoPath = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath); `
}
}
If I add the folder creation and save image logic to the onclick() directly it shows error stating "Failure delivering result info"
*Please do help *
public void saveBitmapToFile(Bitmap bmp) {
File mAppBaseDir;
if (isExternalStorageWritable())
mAppBaseDir = new File(Environment.getExternalStorageDirectory(), "FolderName");
else
mAppBaseDir = new File(getApplicationContext().getFilesDir().getParent()).getAbsoluteFile();
if (!mAppBaseDir.exists()) {
mAppBaseDir.mkdirs();
}
File imageDir = new File(mAppBaseDir, "Profile");
if (!imageDir.exists())
imageDir.mkdirs();
File file = new File(imageDir + "/" + "profile.png");
if (file.exists()) {
file.delete();
}
try {
writeBytesToFile(file, bitmapToByte(bmp));
} catch (IOException e) {
// show alert for retry choose photo
e.printStackTrace();
}
}
public void writeBytesToFile(File file, byte[] bytes) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
Log.e("", e.getMessage());
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
} catch (Exception e) {
Log.e("", e.getMessage());
}
}
}
}
public byte[] bitmapToByte(Bitmap bitmapFinally) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapFinally.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
I answer this question based on your comment "can you please elaborate". CMIIW :
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
folder = new File(Environment.getExternalStorageDirectory() + File.separator + "folder/");
if (!folder.exists())
{
folder.mkdirs();
Log.d("SDcard", "Folder created");
} else {
Log.d("SDCard", "Folder already exists");
}
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "folder/");
Uri photoPath = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
"Ive declared the cameraIntent object before oncreate() method" that's no problem about that, but onActivityResult will be triggered after you call startActivityForResult, then the intent wont have the extra you give
I am having a problem capturing an image and storing it from the native camera app. Here is a sample of some of my code.
_path = Environment.getExternalStorageDirectory() + "make_machine_example.jpg";
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, 0 );
After the picture has been taken and I'm returned back to my original Activity, When I navigate to my sd card via Android DDMS File Explorer the picture is not there. Anyone know why this is not being saved?
Here was the final product in case anyone is still visiting this thread:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
}
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
protected void startCameraActivity() {
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
} catch (Exception e) {
e.printStackTrace();
}
finish();
startActivity(new Intent(CameraCapture.this, Home.class));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Have you checked what the output of Environment.getExternalStorageDirectory() is, because if it does not contain a trailing file seperator (/) then your image will end up in a directory that does not reside on the SDcard such as:
/mnt/sdcardmake_machine_example.jpg
When what you really want is:
/mnt/sdcard/make_machine_example.jpg
Try this code instead:
_path = Environment.getExternalStorageDirectory() + File.separator + "make_machine_example.jpg";
1 . Just use
new File(Environment.getExternalStorageDirectory(), "make_machine_example.jpg");
and don't bother about separators.
2 . Faced the same problem before. SenseUI phones have a custom camera application that doesn't create file. What device are you using? It may already be fixed in latest devices but it may also still be an issue. So here's a complete sample how to overcome it Problems saving a photo to a file.
You should perform a media scanning after saving the image
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Add this line into AndroidManifest.xml file and remove extension make_machine_example:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It will start to capture the Photo and store into the SDcard.