inconsistancy in writing image to hardware in android - android

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());
}

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.

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.

Related

java.io.fileNotFoundException(Permission denied)

I have the next method :
public void saveOnSDCard() {
File path = new File("storage/sdcard1");
File dir = new File(path + "");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "test.png");
OutputStream os;
try {
os = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
} catch (IOException ioe) {
showToast("Ошибка " + ioe.toString());
}
}
but when i try to call it, it gives me a java.io.fileNotFoundException(Permission denied).
I have the next permission in my Manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So can someone tell me what's wrong ?
P.S image - Bitmap object, i declared it in another method.
try if one of the following solutions works:
replace "storage/sdcard1" with"storage/sdcard1/"
replace path + "" with path + "/"
replace "test.png" with "/test.png"
I think it's just missing a slash in one of those three lines
Guy in comment told me that if you have an android 4.4+ you can write to sdcard only when you make your sdcard as primary memory or sometimes when ur phone is rooted. I tried it and it really works.

Create a file on Android Internal Storage?

I'm trying to write a text file in android's internal storage and browse through connecting it to a PC via usb. Now, I used the following code which worked fine for old devices with SD cards.
public void writeToFile(String stringToBeWritten)
{
final File path =
Environment.getExternalStoragePublicDirectory
(
Environment.DIRECTORY_DCIM + "/Target Folder/"
);
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, "MyFile.txt");
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(stringToBeWritten);
System.out.println("Written Successfully");
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
I've been surfing for a solution a while and tried a lot of thing to get my job done. All the solutions out there, to store the file internally but unable to browse.
Any ideas how to write my files on internal phone storage? I'd highly appreciate any help/suggestions. Thanks.

Android delete all files starting with particular word

I have a problem and I hope you can help me out.
In my wallpaper app, I am saving an image to SDcard so the user can share it online via ActionBar share function.
Here is the code that does the saving:
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
Now, I am trying to delete that image when the user leaves the activity (which means he already shared the image or decided not to share. Either way, its not needed anymore.)
I am trying to delete it with this code (Its on button click method atm, but will change that later)
case R.id.btn_delete:
// File folder = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
File folder = new File(Environment.getExternalStorageDirectory() + Environment.DIRECTORY_DOWNLOADS);
File[] filenamestemp = folder.listFiles();
for (int i = 0; i < filenamestemp.length; i++) {
if (filenamestemp[i].getAbsolutePath().toString().contains("share_image_"))
filenamestemp[i].delete();
}
break;
The way I see it, this should work...but it doesn't.
I tried all sorts of things, but nothings works. No errors,nothing..but image is still present in Downloads directory.
Any help?
I think you are getting the wrong directory for the written files
You are reading the files by
File folder = new File(Environment.getExternalStorageDirectory() + Environment.DIRECTORY_DOWNLOADS);
instead of:
File folder = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
These directories are not the same.
Hope it helps, if you need anything else tell me ;)

Saved Bitmap doesn't appear on SD Card

I am working on an app in which I would like to save some Bitmaps to the SD Card. I have looked at a lot of examples and other questions, and from that I have made the following code:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
boolean created = file.createNewFile();
Log.d("Checks", "File created: " + created);
fileOutPutStream = new FileOutputStream(file);
fileOutPutStream.write(byteArrayOutputStream.toByteArray());
fileOutPutStream.close();
} catch (FileNotFoundException e) {
Log.d("Checks", "FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
Log.d("Checks", "IOException");
Log.d("Checks", e.getMessage());
e.printStackTrace();
}
I don't see what's wrong with this code. It doesn't give any errors and my app runs without crashing. However, when I connect my phone to my computer and open the SD Card I do not see the folder "myFolder" and I can not find the saved image anywhere. Do you guys have any ideas as to why this is?
EDIT: I noticed that I can see the saved bitmaps in the Android gallery, and they are indeed in a folder called "myFolder". However, I still don't see them when I connect my phone to my computer and browse my sd card.
From my experience I had similar issued when I forgot the fileOutPutStream.flush(); before the close().
Are you sure you are setting the permission to write to SD card? Try setting this one:
WRITE_EXTERNAL_STORAGE
Edit:
Ok, try this:
Environment.getExternalStorageDirectory().getAbsolutePath()
Instead of:
Environment.getExternalStorageDirectory().toString()
Or even create a directory like this:
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator +
"myFolder");
dir.mkdirs();

android error trying to write to external SD

I am trying to write a jpg image to the external SD card. However, I am getting System.err FileNotFoundException: /mnt/sdcard/test.images/temp/savedImage (no such file or directory). Creating the directory also seems to fail and gives a false in LogCat and I also cannot see the folder when looking on my SD card.
My code is as follows:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File folder = new File(Environment.getExternalStorageDirectory() + "/test.images/temp");
try {
if(!folder.exists()){
boolean dir = new File(Environment.getExternalStorageDirectory() + "/test.images/temp").mkdir();
Log.v("creating directory", Boolean.toString(dir));
}
File imageOutputFile = new File(Environment.getExternalStorageDirectory() + "/test.images/temp", "savedImage");
FileOutputStream fos = new FileOutputStream(imageOutputFile);
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and have cleaned and rebuilt.
Use mkdirs() instead of mkdir().
Guido posted a solution that works for me in the comment. I am going to repeat it just to make sure it can be an answer.

Categories

Resources