I face a problem when downloading an image from remote server. The image is initially transparent but when I download it the transparency changes into a black background.
Callable.invoke(new Callable<Response>() {
#Override
public Response call() throws Exception {
return service.getImage(image);
}
}, new TaskCallback<Response>() {
#Override
public void success(final Response result) {
try {
InputStream in = result.getBody().in();
Bitmap b = BitmapFactory.decodeStream(in);
String mDirectoryPathname = Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)+ "/images/";
String timestamp = new SimpleDateFormat("yyyyMMdd'_'HHmmssSSS")
.format(new Date());
String filename = timestamp + ".png";
final Uri uri = ImageDownloadUtils.createDirectoryAndSaveFile(
context,
b,
filename,
mDirectoryPathname);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void error(Exception e) {
Log.e(TAG, "Error getting image via OAuth.", e);
}
});
Here is the factory method which is called to save the image.
public static Uri createDirectoryAndSaveFile(Context context,
Bitmap imageToSave,
String fileName,
String directoryPathname) {
if (imageToSave == null)
return null;
File directory = new File(directoryPathname);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, getTemporaryFilename(fileName));
if (file.exists())
file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG,
100,
outputStream);
outputStream.flush();
} catch (Exception e) {
return null;
}
String absolutePathToImage = file.getAbsolutePath();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, fileName);
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
file.getName().toLowerCase(Locale.US));
values.put("_data",
absolutePathToImage);
ContentResolver cr = context.getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
return Uri.parse(absolutePathToImage);
}
This is not the problem with image's transparency. When you download an image and view it in Gallery, it is showing the image in an ImageView. That ImageView has a default background of black colour. That's why the transparent part of the downloaded image appears as black.
If you are showing the image in your application, set the background of ImageView to transparent.
android:background="#android:color/transparent"
in XML or
imageView.setBackgroundColor(Color.TRANSPARENT);
through code.
EDIT: If still the problem persists, try this :
InputStream in = result.getBody().in();
Bitmap b = BitmapFactory.decodeStream(in);
String mDirectoryPathname = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/images/";
String timestamp = new SimpleDateFormat("yyyyMMdd'_'HHmmssSSS").format(new Date());
String filename = timestamp + ".png";
try {
File file = new File(mDirectoryPathname, filename);
FileOutputStream outputStream = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
final Uri uri = Uri.fromFile(file);
Related
i m working on an application where i have list of images inside recyclerview and from recyclerview i have to copy my images from one folder to another folder my code is working fine in many android 11 and 12 device but in few device it creates blank images the size of blank image is in byte i don't understand what is wrong with my code
here is the code i used for copy image
public static String copyFile(#NonNull final String filePath, String newName, File targetFolder, Context context) {
ContentResolver contentResolver = context.getContentResolver();
FileOutputStream fos = null;
String folderName = targetFolder.getName();
String relativePath;
String fileName = new File(filePath).getName();
String mimeType = getFileType(fileName);
ArraySet<Uri> uries = new ArraySet<>();
if (isImage(mimeType)) {
uries.add(getImageUriFromFile(filePath, context));
} else {
uries.add(getVideoUriFromFile(filePath, context));
}
if (targetFolder.getPath().contains(Environment.DIRECTORY_PICTURES)) {
relativePath = Environment.DIRECTORY_PICTURES + File.separator + folderName;
} else if (targetFolder.getPath().contains(Environment.DIRECTORY_DCIM)) {
relativePath = Environment.DIRECTORY_DCIM + File.separator + folderName;
} else {
relativePath = Environment.DIRECTORY_PICTURES + File.separator + folderName;
}
try {
if (isImage(new File(filePath).getName().split("\\.")[1])) {
Bitmap bitmap = getBitmap(filePath);
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, newName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath);
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = (FileOutputStream) contentResolver.openOutputStream(imageUri);
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
fos.flush();
}
return getPath(imageUri, context);
} else {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, newName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/" + mimeType);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath);
Uri imageUri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = (FileOutputStream) contentResolver.openOutputStream(imageUri);
FileInputStream inStream = new FileInputStream(filePath);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = fos.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
fos.close();
return getPath(imageUri, context);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
and i called this method inside thread like below.
i called this method from thread because i m doing another operation on copied file
new Thread(() -> StorageUtils.copyFileOnAboveQ(
file1.getPath(),
file2.getName().split("\\.")[0],
file2.getParentFile(), context)).start();
code is working fine in many devices but in some device it create blank image
So, I am creating a QRCode generator application in which user can generate QR code from the data they have entered.I can successfully generate the QR code and show it to the imageview on a Button click but I am facing issue when I tried to save that QR code to my phone's storage (or gallery).
On this button click, QRGenerator function will be called and It will generate the QR code from the Edittext data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
QRGenerator();
}
});
Here is the QRGenerator() funcion :
private void QRGenerator() {
String data = text.getText().toString();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(data, BarcodeFormat.QR_CODE, 300, 300);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
imgView.setImageBitmap(bitmap);
bitmap2 = ((BitmapDrawable)imgView.getDrawable()).getBitmap();
saveImg.setVisibility(View.VISIBLE);
} catch (WriterException e) {
e.printStackTrace();
}
}
and from here I can call the save image function :
saveImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveImageFunction(bitmap2);
}
});
and here my issue arise, I have put a Toast to notify when my image will saved to gallery but it never pops up
Here is the saveImageFunction :
private void saveImageFunction(Bitmap bitmap) {
String savedImagePath = null;
String imageFileName = "JPEG_" + "test" + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Demo");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
addToGallery(savedImagePath);
Toast.makeText(MainActivity.this,"Saved to Gallery!",Toast.LENGTH_SHORT).show();
}
}
and to put that saved image to gallery I have used this function :
addToGallery() :
private void addToGallery(String imagePath){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
As per Gk Mohammad Emon says, I tried adding Toast as well as Log.d in my catch method of SaveImage function but nothing pops up neither on Screen nor in LogCat (Please address any type of mistake if there) :
private void saveImageFunction(Bitmap bitmap) {
String savedImagePath = null;
String imageFileName = "JPEG_" + "test" + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Demo");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
Toast.makeText(MainActivity.this,"Image Saved!", Toast.LENGTH_SHORT).show();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"hello There",Toast.LENGTH_SHORT).show();
Log.d("Exception e",e.toString());
}
addToGallery(savedImagePath);
Toast.makeText(MainActivity.this,"Saved to Gallery!",Toast.LENGTH_SHORT).show();
}
}
Here i am making drawable view into bitmap.
mDrawingPad.setVisibility(View.VISIBLE);
BitmapDrawable ob = new BitmapDrawable(getResources(),
bitmapconv);
DrawingView mDrawingView=new
DrawingView(Previewimage.this);
mDrawingPad.addView(mDrawingView);
mDrawingView.setBackground(ob);
mDrawingView.buildDrawingCache();
drawbitmap=mDrawingView.getDrawingCache();
I need to convert this into URI to send to image cropper library
CropImage.activity(uri).start(Previewimage.this);
/*This saveImage method will return String path*/
path = saveImage();
Uri uri = Uri.parse(path);
/****************************************************/
private String saveImage()
{
Bitmap bitmap;
mDrawingView.setDrawingCacheEnabled(true);
mDrawingView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mDrawingView.buildDrawingCache();
bitmap = Bitmap.createBitmap(mDrawingView.getDrawingCache());
String state = Environment.getExternalStorageState();
String root = "";
String fileName = "/MyImage" + System.currentTimeMillis() + "Image"+ ".jpg";
String parent = "App_Name";
File mFile;
if (Environment.MEDIA_MOUNTED.equals(state)) {
root = Environment.getExternalStorageDirectory().toString();
mFile = new File(root, parent);
if (!mFile.isDirectory())
mFile.mkdirs();
} else {
root = FriendsImageSending.this.getFilesDir().toString();
mFile = new File(root, parent);
if (!mFile.isDirectory())
mFile.mkdirs();
}
String strCaptured_FileName = root + "/App_Name" + fileName;
File f = new File(strCaptured_FileName);
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, bytes);
FileOutputStream fo;
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
bitmap.recycle();
System.gc();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return strCaptured_FileName;
}
This part of code works:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
your_bitmap_image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(your_context.getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
just try to replace the areas that I mentioned in it
in the place of "your_context" if you are in an activity put this:
MediaStore.Images.Media.insertImage(getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
if you are in a fragment :
MediaStore.Images.Media.insertImage(getContext().getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
Use this method:
public Uri getImageUri(Context ctx, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(ctx.getContentResolver(),
bitmap, "Temp", null);
return Uri.parse(path);
}
If you are calling this method inside an Activity then call this method like this:
getImageUri(YourClassName.this, yourbitmap);
But if you are calling this in an Fragment then call like this:
getImageUri(getActivity(), yourbitmap);
I try to save the image into WathsappIMG but when I go to image gallery android I don't see the image and the image there into the directory can be seen from ES File Explorer
OutputStream output;
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/WhatSappIMG/");
dir.mkdirs();
// Retrieve the image from the res folder
BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable();
Bitmap bitmap1 = drawable.getBitmap();
// Create a name for the saved image
File file = new File(dir, "Wallpaper.jpg" );
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the gallery don't displaying (necessarily) files from external storage.
this is a common mistake.
the gallery displays images stored on the media store provider
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
here is what you should enter, when you're about to save the picture in the Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
That code will add the image at the end of the Gallery. so please, check your Gallery picture, to be sure
Try adding this:
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Fill in your details for yourBitmap, yourTitle, and yourDescription, or just leave it as "".
You need to add a MediaScannerConnection class to your function of saving the image to the gallery. This class scans for new files and folders in gallery connected with your app. Add the following class to scan the newly saved image files or new added image directory to the gallery or download Source Code
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Read more
For Xamarin fellows:
public static void SaveToTheGalley(this string filePath, Context context)
{
var values = new ContentValues();
values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
values.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/jpeg");
values.Put(MediaStore.MediaColumns.Data, filePath);
context.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
}
And don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission.
As
MediaStore.MediaColumns.Data
and
MediaStore.Images.Media.insertImage
is deprecated now,
here is how I did it using bitmap
fun addImageToGallery(
fileName: String,
context: Context,
bitmap: Bitmap
) {
val values = ContentValues()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
}
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
val uri: Uri? = context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
uri?.let {
context.contentResolver.openOutputStream(uri)?.let { stream ->
val oStream =
BufferedOutputStream(stream)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
oStream.close()
}
}
}
You should change this piece of code-
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
String url = Images.Media.insertImage(getContentResolver(), bitmap1,
"Wallpaper.jpg", null);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly refer this code worked for me:
public static boolean saveImageToGallery(Context context, Bitmap bmp) {
// First save the picture
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
//Compress and save pictures by io stream
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
//Insert files into the system Gallery
//MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//Update the database by sending broadcast notifications after saving pictures
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
Use the following code to make your image visible in the gallery.
public void saveImageToGallery(Context context, Uri path) {
// Create image from the Uri for storing it in the preferred location
Bitmap bmp = null;
ContentResolver contentResolver = getContentResolver();
try {
if(Build.VERSION.SDK_INT < 28) {
bmp = MediaStore.Images.Media.getBitmap(contentResolver, path);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, path);
bmp = ImageDecoder.decodeBitmap(source);
}
} catch (Exception e) {
e.printStackTrace();
}
// Store image to internal storage/ImagePicker directory
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ImagePicker";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
// Broadcast the image & make it visible in the gallery
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
Toast.makeText(context, "File saved to gallery", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Failed to save", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
I have created a program to capture the image and that is getting stored into sdcard/dcim/camera folder. Now I am trying to save the captured image in my own directory created in sdCard, say "/somedir".
I am able to make the directory programmatically but the image file is not getting stored in it.
Can anybody tell me where I am doing wrong here??
Here is the code....
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
Bitmap mybitmap1; //mybitmap1 contain image. So plz dont consider that I don't have image in mybitmap1;
if(!folder.exists())
{
success = folder.mkdir();
Log.i("Log", "folder created");
}
else
{
Log.i("Log", "Folder already present here!!");
}
String fname = date +".jpg";
file = new File( folder,fname);
if (file.exists ())
file.delete ();
capturedImageUri = Uri.fromFile(file);
FileOutputStream out;
byte[] byteArray = stream.toByteArray();
try {
out = new FileOutputStream(file);
mybitmap1.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), mybitmap1, file.getName(), file.getName());
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
}
Refer the below code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == 1 ) {
final Uri selectedImage = data.getData();
try {
bitmap = Media.getBitmap(getContentResolver(),selectedImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ filename);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are settings the wrong file name for the file. Just use this method if you want to use time in the name of image file.
private Uri getImageUri() {
// Store image in dcim
String currentDateTimeString = getDateTime();
currentDateTimeString = removeChar(currentDateTimeString, '-');
currentDateTimeString = removeChar(currentDateTimeString, '_');
currentDateTimeString = removeChar(currentDateTimeString, ':');
currentDateTimeString = currentDateTimeString.trim();
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM", currentDateTimeString + ".jpg");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}
private final static String getDateTime() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
return df.format(new Date());
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
return r.toString();
}
Hers is what you need to do:
instead of
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
do this
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/abc");
if(folder.exists()){
//save your file then
}
else{
folder.mkdirs();
//save your file then
}
Make sure you use the neccessary permissions in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>