How to test for a file in cache? - android

I am trying to test for this cache in my asyncTask. How would i go about doing this?
public void putBitmapInDiskCache(URI imageUri, Bitmap avatar) {
File cacheDir = new File(this.getCacheDir(), "thumbnails");
cacheDir.mkdirs();
File cacheFile = new File(cacheDir, ""+imageUri.hashCode());
try {
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
avatar.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("error", "Error when saving image to cache. ", e);
}

Based on what you have. If prior to your call to createNewFile() you were to check if it exists, you can do whatever needs to be done there
if (cacheFile.exists()) { ... } else { cacheFile.createNewFile() }

Related

how can i change bitmap saving location

How can change image saving location i have created the folder but how to save image in it. all downloaded images are saved in pictures folder
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
file = new File(Environment.getExternalStorageDirectory().getPath() + "/CreativeGraphy");
if (!file.exists()) {
file.mkdir();
}
try {
file.createNewFile();
MediaStore.Images.Media.insertImage(r, bitmap, name, desc);
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
Toast.makeText(context, "Download succeed ", Toast.LENGTH_SHORT).show();
}
Use this method
public static void saveBitmap(String path, Bitmap bitmap) {
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
After saving you can call scanFile method to index your file in the gallery.
MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
thanks everyone This works
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CreativeGraphy";
File dir = new File(file_path);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir,name );
FileOutputStream fOut;
try {
MediaStore.Images.Media.insertImage(r, bitmap, name, desc);
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
Toast.makeText(context, "Download succeed ", Toast.LENGTH_SHORT).show();
}

Failing to store bitmap as a file

Im trying to save a bitmap as a file however its failing for some reason
Thats the error I keep getting, it only pops up on 5.0 however I tested it on 6.0 sdk and its working fine
java.io.FileNotFoundException: /storage/sdcard/Pictures/mFile/image1491238127.jpg: open failed: EISDIR (Is a directory)
private File saveBitmap(Bitmap bitmap, String path) {
File file = null;
if (bitmap != null) {
file = new File(path);
file.mkdirs();
try {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
}
private File saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-Fashom" +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
As I observe on your code I found you creating file.mkdir(); it means you creating a new file not get u need to write the code after try catch return exception.
try {
//it gets file path
file = new File(path);
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
ting the exist file..

(android) how to overwrite image on DCIM folder?

I already have a resized bitmap object.
with this bitmap, how can i overwrite this bitmap in DCIM folder??
I know that I should change the bitmap into File object...
please help me
(Assume that i also have the absolute path)
I tried this with the code below.
It creates a new file only if a file with same name doesn't exist.
Otherwise, it doesn't create a new file.
private void SaveBitmapToFileCache(Bitmap bitmap, String strFilePath) {
File fileCacheItem = new File(strFilePath);
OutputStream out = null;
try
{
fileCacheItem.createNewFile();
out = new FileOutputStream(fileCacheItem);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Try something like this:
//File file= new File("FilePath"+ "/myfolder/myimage.jpg");
if(fileCacheItem .exists())
{
file.delete();
}

All my images are public to all android installed apps

I'm using this code to save images in the SD card (simulated or real) but all the testers of my app are telling me that the have a new folder in their Photos app with all my images (I don't know why on my Nexus 4 with KK this is not happening).
static public void storeImage(Bitmap image, String imgName) {
String root = Environment.getExternalStorageDirectory().toString();
File myRoot = new File(root + "/files");
if (!myRoot.exists()) {
myRoot.mkdir();
}
File myDir = new File(root + "/images/");
if (!myDir.exists()) {
myDir.mkdir();
}
File file = new File(BasePathToFile(imgName));
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to change de visibility, security or something to avoid that the Photos App or any App get access to my folder??
After reading a lot I have found this in the android dev page.
So at the end if you want that your files remain private you have to store them in the device.
So I have change my code to this:
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(context.getFilesDir(), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I hope this will be useful to someone.
Happy coding.
A #Sebastian pointed getExternalFilesDir(String type) is a more complete solution so i have changed de code to this:
private static Boolean SdMemoryExist() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
static public String BasePath(Context context) {
String _basePathToCheck;
if (SdMemoryExist()) {
_basePathToCheck = context.getExternalFilesDir(null).toString() + File.separator;
} else {
_basePathToCheck = context.getFilesDir().toString() + File.separator;
}
return _basePathToCheck;
}
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(BasePath(context), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding.

Storing serialized objects into sdcard as file causing FileNotFoundException

I want to serialize an object and store it inside sdcard under my project name but I'm getting FileNotFoundException.
My code is written below:
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
File dir = new File(Environment.getExternalStorageDirectory(), FILE_LOCATION + username);
try {
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, FILE_NAME);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(formList);
objectOutputStream.close();
} catch(IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
What is the reason for this issue? I'm running in emulator and my application is in android 3.0.
I suspect your filename is invalid, maybe that . in the directory? Or the file-name its self.
Correct me if I'm wrong, but don't you have to create the File before you write to it?
File file = new File(dir, FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
I would like to share my solution for this since I got a lot of help from Stackoverflow on this issue (by searching for previous answers). My solution resulted for a couple of hours of searching and piecing together solutions. I hope it helps someone.
This will write and read an ArrayList of custom objects to and from External Storage.
I have a class that provides IO to my activities and other classes. Alarm is my custom class.
#SuppressWarnings("unchecked")
public static ArrayList<Alarm> restoreAlarmsFromSDCard(String fileName,
Context context) {
FileInputStream fileInputStream = null;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();//Alarm is my custom class
//Check if External storage is mounted
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
Log.v("FileIOService", "No Such Directory Exists");
}
File file = new File(dir, fileName);
fileInputStream = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fileInputStream);
alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Do something here to warn user
}
return alarmList;
}
public static void saveAlarmsToSDCard(String fileName, ArrayList<Alarm> alarmList,Context context) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(alarmList);
objectOutputStream.close();
} catch (IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
}else{
//Do something to warn user that operation did not succeed
}
}

Categories

Resources