android download image to sd-card and then read it from sd-card

血红的双手。 提交于 2019-12-13 03:49:15

问题


hi to all i have this problem with my code and i tried every thing that i know of and i posted it on some forums and didnt get an answer im new to android and im still learning .....

my question is that i have a code that is suppose to receive a variable that contains a website that has an image so this variable changes every time i send a new link this code should go online and download the image and save it to the sd-card then i read it and display it

so my problem with the code is if im sending 2 links to it, it downloads 1 of the images and it always stores it with the second image name (example: im sending image1 and image2 the code downloads image1 two times and stores it as "image2") when i mount the sd-card and check the image directory there is only 1 image there named image2, i thought that doInBackground was causing the problem but im also using onPostExecute() so please if someone can help me i would be thankful for his help Note this is how i call it:

locLink = getLocalLink(buffer[3], buffer[0]);

buffer[3] = image website (example:http://www.oceanwideimages.com/images/7049/large/24M2444-16-palm-fringed-tropical-island.jpg)

buffer[0] = new file name (example 1 as a string)

this is the code:

private 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 = ImageLink.substring(ImageLink
                    .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 image "
                    + 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, "image/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();
    }

and this is how i read it:

String imageInSD = c.getString(5); //"/sdcard/Hanud/image1.jpg"or image2;
            Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
            myImageView=(ImageView)findViewById(R.id.imageview1);
            myImageView.setImageURI(null);
            myImageView.setImageBitmap(bitmap);

来源:https://stackoverflow.com/questions/5766430/android-download-image-to-sd-card-and-then-read-it-from-sd-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!