0

我将 10 张图片从 web 加载到 sd 卡,我的代码在 sd 卡中创建了子文件夹并加载了所有 10 张图片,但在那之后只有第 1 次它没有加载和存储任何图像,logcat 也没有错误。这是我的代码:

reviewImageLink = u_image;
                 URL reviewImageURL;
                String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
                    try {
                        reviewImageURL = new URL(reviewImageLink);
                        if (!hasExternalStoragePublicPicture(name)) {
                            isImage = false;
                            new DownloadImageTask().execute(reviewImageURL);
                            Log.v("log_tag", "if");
                            isImage = true;
                            File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources().getString(R.string.directory));
                            sdImageMainDirectory.mkdirs();
                            file = new File(sdImageMainDirectory, name);
                            Log.v("log_tag", "Directory created");
                        }

                    } catch (MalformedURLException e) {
                        Log.v(TAG, e.toString());
                    }

下载图像任务:

class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
    // This class definition states that DownloadImageTask will take String
    // parameters, publish Integer progress updates, and return a Bitmap
    protected Bitmap doInBackground(URL... paths) {
        URL url;
        try {
            url = paths[0];
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int length = connection.getContentLength();
            InputStream is = (InputStream) url.getContent();
            byte[] imageData = new byte[length];
            int buffersize = (int) Math.ceil(length / (double) 100);
            int downloaded = 0;
            int read;
            while (downloaded < length) {
                if (length < buffersize) {
                    read = is.read(imageData, downloaded, length);
                } else if ((length - downloaded) <= buffersize) {
                    read = is.read(imageData, downloaded, length
                            - downloaded);
                } else {
                    read = is.read(imageData, downloaded, buffersize);
                }
                downloaded += read;
                publishProgress((downloaded * 100) / length);
            }
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                    length);
            if (bitmap != null) {
                Log.i(TAG, "Bitmap created");
            } else {
                Log.i(TAG, "Bitmap not created");
            }
            is.close();
            return bitmap;
        } catch (MalformedURLException e) {
            Log.e(TAG, "Malformed exception: " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.toString());
        }
        return null;

    }

    protected void onPostExecute(Bitmap result) {
        String name = reviewImageLink.substring(reviewImageLink
                .lastIndexOf("/") + 1);
        if (result != null) {
            hasExternalStoragePublicPicture(name);
            saveToSDCard(result, name);
            isImage = true;

        } else {
            isImage = false;

        }
    }
}

public void saveToSDCard(Bitmap bitmap, String name) {
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
        Log.v(TAG, "SD Card is available for read and write "+ mExternalStorageAvailable + mExternalStorageWriteable);
        saveFile(bitmap, name);
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
        Log.v(TAG, "SD Card is available for read "+ mExternalStorageAvailable);
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
        Log.v(TAG, "Please insert a SD Card to save your Video "+ mExternalStorageAvailable + mExternalStorageWriteable);
    }
}

private void saveFile(Bitmap bitmap, String name) 
{
    String filename = name;
    ContentValues values = new ContentValues();
    File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources().getString(R.string.directory));
    sdImageMainDirectory.mkdirs();
    File outputFile = new File(sdImageMainDirectory, filename);
    values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
    values.put(MediaStore.MediaColumns.TITLE, filename);
    values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "output.png");
    Uri uri = this.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);

    try 
    {
        OutputStream outStream = this.getContentResolver().openOutputStream(uri);
        bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);
        outStream.flush();
        outStream.close();
    }
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    } catch (IOException e) 
    {
        e.printStackTrace();
    }
}

private boolean hasExternalStoragePublicPicture(String name) {
    File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources().getString(R.string.directory));
    File file = new File(sdImageMainDirectory, name);
    if (file != null) 
    {
        file.delete();
    }
    return file.exists();
}

这是 logcat :

02-20 08:49:46.999: D/dalvikvm(346): GC_FOR_MALLOC freed 5254 objects / 245320 bytes in 69ms
02-20 08:50:00.138: I/Topten(346): Bitmap created
02-20 08:50:00.148: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:03.628: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 4548 objects / 238192 bytes in 68ms
02-20 08:50:03.728: I/Topten(346): Bitmap created
02-20 08:50:03.738: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:04.898: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 585 objects / 85272 bytes in 107ms
02-20 08:50:05.018: I/Topten(346): Bitmap created
02-20 08:50:05.049: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:05.528: I/Topten(346): Bitmap created
02-20 08:50:06.409: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:10.968: I/Topten(346): Bitmap created
02-20 08:50:10.968: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:12.368: I/Topten(346): Bitmap created
02-20 08:50:12.380: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:15.569: D/dalvikvm(346): GC_EXTERNAL_ALLOC freed 4584 objects / 358728 bytes in 58ms
02-20 08:50:15.619: I/Topten(346): Bitmap created
02-20 08:50:15.629: V/Topten(346): SD Card is available for read and write truetrue
02-20 08:50:22.179: I/Topten(346): Bitmap created
02-20 08:50:22.189: V/Topten(346): SD Card is available for read and write truetrue
4

2 回答 2

1

编辑: 您的代码似乎是正确的..我没有发现任何错误。我不确定是否是原因但是..在创建目录之前检查目录是否存在

if(!sdImageMainDirectory.exists()){
sdImageMainDirectory.mkdirs();
}

检查一次并回复我...进一步分析...我希望这会对您有所帮助。


您还没有将文件写入外部存储您刚刚创建了一个文件...尝试将文件写入外部存储并确保您已设置权限外部存储写入

于 2013-02-20T17:52:21.853 回答
0

如果我没记错的话,你的变量reviewImageLink是一个类变量。然后,在您的 DownloadImageTask 中,您使用reviewImageLink生成文件名并将您的图像保存在此文件中。

问题是:如果你调用你的函数 10 次,一个接一个,你的类变量reviewImageLink将被最后一次调用覆盖。这可能会导致您的应用始终只保存一张图片。

我的建议是您可以在 DownloadImageTask 中生成图像文件名。所以下载完成后,它会将图像文件保存在单独的文件中。

这是我下载图像并保存在本地的方法。我把下载和保存放在 AsyncTask 类中。我还决定了 AsyncTask 中的文件名。所以其他下载过程之间没有冲突。请检查我的DownloadImageTask类。

http://jmsliu.com/1929/android-progress-dialog-example.html

于 2014-02-14T09:12:23.340 回答