【问题标题】:AsyncTask - Download image - decode stream ErrorAsyncTask - 下载图像 - 解码流错误
【发布时间】:2016-03-15 20:58:47
【问题描述】:

我想创建一个应用程序,它允许使用 URL 地址下载图片,然后将其显示在我的屏幕上。 不幸的是,在 LogCat 中显示了这个错误:

BitmapFactory:无法解码流:java.io.FileNotFoundException:sdcard/photoalbum/download_image.jpg:打开失败:ENOENT(没有这样的文件或目录)

屏幕上显示的下载进度非常快。图像有 12 KB。 但我看到这张图片没有下载到我的手机(sdcard)上。 这是因为我无法解码这个流吗?

如果有人知道如何解决/修复此问题,我将不胜感激?

这是一个代码:

ImageView imageView;

String image_url = "http://montco.happeningmag.com/wp-content/uploads/2015/04/run-150x150.jpg";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    imageView = (ImageView) findViewById(R.id.image_view);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DownloadTask downloadTask = new DownloadTask();
            downloadTask.execute(image_url);


        }
    });

}

// how to create an assign task do download this image

class DownloadTask extends AsyncTask<String,Integer,String> // second type is Integer because this is from 'int progress', third is String because this is the return ("Download Complete...")
{

    // progress bar to display this download

    ProgressDialog progressDialog;


    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("Download in Progress...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        // how is the maximum size of this file, we need some variable:
        int file_length = 0;

        String path = params[0]; // we get this URL , 0(zero) index of this argument
        // how image_url on this variable call "path"
        try {
            URL url = new URL(path);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            file_length = urlConnection.getContentLength();
            // we need a folder to storage this download image
            File new_folder = new File("sdcard/photoalbum");
            if(!new_folder.exists())
            {
                new_folder.mkdir(); // we create new folder if 'photoalbum' doesnt exist in sdcard
            }
            // how to put some file inside this folder
            File input_file = new File(new_folder,"downloaded_image.jpg");
            // how to create input STREAM to read information data from url
            InputStream inputStream = new BufferedInputStream(url.openStream(),8192); // we need input stream with some buffer. 8192(8 KB) (input stream
            // now I want to read informations in one kb so I need byte variable
            byte[] data = new byte[1024]; // it will read info to 1 KB
            // before read information we need some variable
            int total = 0;
            int count = 0;
            // we need output stream object to write a data
            OutputStream outputStream = new FileOutputStream(input_file); // because outputStream is available in input_file
            // we need write information to outputStream
            while((count = inputStream.read())!=-1) //loop executes until the value became (-1)
            {
                // how to update value from a variable total
                total += count;
                outputStream.write(data,0,count); // data is available on the Byte variable data; offset; count
                // how to display a progress bar: we need to call publish progress method and specify special value for this progress
                int progress = (int) total*100/file_length;
                publishProgress(progress);

            }

            // how to close Stream
            inputStream.close();
            outputStream.close();



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // after finished our job we need to return some result
        return "Download Complete...";
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progressDialog.setProgress(values[0]); // this will update the progress bar
    }

    @Override
    protected void onPostExecute(String result) {
        // after finishing job, we need to hide a progress bar
        progressDialog.hide();
        // how to display some result
        Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
        // how to put image into imageView
        String path = "sdcard/photoalbum/download_image.jpg";
        // how to set this image in imageView
        imageView.setImageDrawable(Drawable.createFromPath(path));

    }


}

【问题讨论】:

  • sdcard/photoalbum 不是有效的文件路径。永远不要硬编码 'sdcard' - 请改用 Environment.getExternalStoragePublicDirectory
  • @adelphus 但是,在这种情况下,当我更改此行时,String path = "sdcard/photoalbum.." 仍然存在无法流问题。我需要使用新的 google 更改我的所有代码结构操作说明?可能会比这段代码难。

标签: java android class android-asynctask


【解决方案1】:
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists()){
    new_folder.mkdir(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}

尝试修改上面的代码如下:

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable()) {
    File new_folder = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "photoalbum");
    if(!new_folder.exists()){
        new_folder.mkdirs(); // we create new folder if 'photoalbum' doesnt exist in sdcard
    }
}

【讨论】:

  • 它仍然不起作用,因为仍然显示相同的错误:无法解码流:java.io.FileNotFoundException:download_image.jpg:打开失败:ENOENT(没有这样的文件或目录)。这个错误几乎是最后一行:String path = ...
  • 我猜该文件不会在 doInBackground() 中保存到文件系统,因此,您在 onPostExecute() 中读取它会捕获执行。尝试在 doInBackground 方法中设置一个断点,并通过它来查找发生了什么错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 2021-02-20
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多