Reputation: 399
I'm having a problem. I'm trying to create a bitmap in a directory on my phone. However it doesn't always work and never seems to work right away. After running if I look in the directory it wont be there, I have to fiddle around in other folders and keep refreshing before it shows up, often it doesn't even show up at all. I do not understand this, any help or insight would be very much appreciated, thanks
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.PNG, 40, bytes);
try {
File f = new File(Environment.getExternalStorageDirectory() + "/myDirectory/" + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
Log.e(TAG, "Was unable to copy image" + e.toString());
}
Upvotes: 0
Views: 37
Reputation: 399
If for some reason someone comes across this with a similar problem, I found out the solution. For whatever reason the file wont show up until I disconnect the phone from the USB cable. The second I do the files show up.
Upvotes: 1
Reputation: 6892
You are trying to create the file without having created the /myDirectory/ folder first, so it may fail to create your file. Also, you must check the return value of f.createNewFile()
, because it will return false if the file already exists. For really checking if the file exists, use f.exists()
instead.
So, if you change your code to:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Log.i("COMPRESSED Bitmap", " "+myImage.compress(Bitmap.CompressFormat.PNG, 40, bytes));
try {
File directory = new File(Environment.getExternalStorageDirectory() + "/myDirectory/");
Log.i("Created external folder successfully", " "+directory.mkdirs());
File f = new File(Environment.getExternalStorageDirectory() + "/myDirectory/" + "test.png");
Log.i("Created external file successfully", " "+f.createNewFile() + " file exists "+ f.exists());
if(f.exists()){
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.e("MyActivity", "Was unable to copy image" + e.toString());
}
It will only write to the file if it already exists. I tested it and the file is always there, and is replaced by another if you execute the code a second or third time.
Upvotes: 0