I’ve designed quickly a piece of code which loads from an specified URL and then saves it to the SD card, however it is not saving to the SD.
URL myFileUrl = new URL( Image_HTML);
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = new FileOutputStream(filepath+image_name);
bm.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bm = BitmapFactory.decodeFile(filepath+image_name);
image_loader_view.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Hub", "FileNotFoundException: "+ e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i("Hub", "IOException: "+ e.toString());
}
I have tried to make this code as lightweight as possible, and I have also activated the EXTERNAL.STORAGE.WRITE in the android manifest.
Couple things.
When you use a FileOutputStream you have to make sure the directory you are trying to write to is created before you try to write a file to it. If not you have to create it. This can be done via
mkdirs()method of theFileclass.Next I’m not sure the call to
getAbsolutePathis required, due to the type of file system Android uses. I’ve never had to use it to save to SD before.I’d try these and see if one of them will solve it for you.