开发者

Android - Save image to SD and then Load Image

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 = B开发者_JAVA技巧itmapFactory.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 the File class.

Next I'm not sure the call to getAbsolutePath is 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜