0

I am using string array to hold images, i am fetching the imaes from the URLs. I have one imageview which when swipped changes the images in it. Now i want to download and save any image i want on the SD card and want it to appear in the phone gallery in a new folder.

I am using the following code but it is not working, it is showing no error at all.

private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... arg0) {
            downloadImagesToSdCard("", "");
            return null;
        }

        private void downloadImagesToSdCard(String downloadUrl, String imageName) {
            try {
                URL url = new URL(thumb[j]);
                /* making a directory in sdcard */
                String sdCard = Environment.getExternalStorageDirectory()
                        .toString();
                File myDir = new File(sdCard, "test.jpg");

                /* if specified not exist create new */
                if (!myDir.exists()) {
                    myDir.mkdir();
                    Log.v("", "inside mkdir");
                }

                /* checks the file and if it already exist delete */
                String fname = imageName;
                File file = new File(myDir, fname);
                if (file.exists())
                    file.delete();

                /* Open a connection */
                URLConnection ucon = url.openConnection();
                InputStream inputStream = null;
                HttpURLConnection httpConn = (HttpURLConnection) ucon;
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    inputStream = httpConn.getInputStream();
                }

                FileOutputStream fos = new FileOutputStream(file);
                int totalSize = httpConn.getContentLength();
                int downloadedSize = 0;
                byte[] buffer = new byte[1024];
                int bufferLength = 0;
                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, bufferLength);
                    downloadedSize += bufferLength;
                    Log.i("Progress:", "downloadedSize:" + downloadedSize
                            + "totalSize:" + totalSize);
                }

                fos.close();
                Log.d("test", "Image Saved in sdcard..");
            } catch (IOException io) {
                io.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

And i am executing it by

new ImageDownloadAndSave().execute("");

the name of my string array is "thumb" which is holding all the URLs. What am i doing wrong?

2 Answers2

0

You should add image to gallery after save and then scan it. Please check the following topics:

Image, saved to sdcard, doesn't appear in Android's Gallery app

MediaScannerConnection

Community
  • 1
  • 1
Tim
  • 1,606
  • 2
  • 20
  • 32
0

The file needs to be added to the Android MediaStore. This can be done easily by using below function.

public void scanFile(final File file) {
    try {
        new MediaScannerConnectionClient() {
            private MediaScannerConnection mMs;

            public void init() {
                mMs = new MediaScannerConnection(myContext, this);
                mMs.connect();
            }

            @Override
            public void onMediaScannerConnected() {
                mMs.scanFile(file.getAbsolutePath(), null); 
                mMs.disconnect();
            }

            @Override
            public void onScanCompleted(String path, Uri uri) {
            }

        }.init();
    } catch(Exception e) {
        // Device does not support adding files manually. 
        // Sending Broadcast to start MediaScanner (slower than adding manually)
        try {   
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        } catch(Exception ee) {
            // Something went terribly wrong. 
            // Can't add file to MediaStore and can't send Broadcast to start MediaScanner.
        }
    }
}

You just need to add one line to your code:

// .....

fos.close();
Log.d("test", "Image Saved in sdcard..");

scanFile(file); // <------------- add this
ByteHamster
  • 4,884
  • 9
  • 38
  • 53