views:

127

answers:

1

Hi,

I had a part of code which suppose to get an image from website and store it into the sdcard. The following code was working find when i develop on sdk1.5. However, it was not working now after i change it to android sdk 2.0. This line got problem; FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);

Here is the code that i have:

  void downloadFile(String fileUrl) {
    URL myFileUrl = null;
    try {
        myFileUrl = new URL(fileUrl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl
                .openConnection();
        conn.setDoInput(true);
        conn.connect();

        InputStream is = conn.getInputStream();

        bmImg = BitmapFactory.decodeStream(is);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        String filepath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        FileOutputStream fos = new FileOutputStream(filepath + "/"
                + this.filename);
        bmImg.compress(CompressFormat.JPEG, 75, fos);
        fos.flush();
        fos.close();

        Context context = this.getBaseContext();
        new MediaScannerNotifier2(context, filepath + "/" + this.filename,
                "image/jpeg");

        // displaying download completion message
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Wallpaper Downloaded").setCancelable(false)
                .setPositiveButton("ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();
                                btn_setwall.setEnabled(true);
                                btn_download.setEnabled(false);
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    } catch (Exception e) {
        Log.e("MyLog", e.toString());
    }

}

The error occur in the 3rd catch. However, when i move this line

FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);

to the 2nd try/catch, then it will occur in the 2nd catch. Can please help me on this?

A: 

Maybe try getting rid of .getAbsolutePath()

This works for me on 2.2:

FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);
NeilMonday