3

I need my android app to make request to url to download an image from this url so I have built this class to help me, BUT it didn't work ???

public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;

    protected void doInBackground() throws IOException {
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");

        try{
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");

            // Open a connection to that URL.
            URLConnection ucon = url.openConnection();

            // Define InputStreams to read from the URLConnection.
            is = ucon.getInputStream();
        } catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute() {
        try {
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(
                null,
                new String[] { file.toString() },
                null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                }
            );
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And I have, in the Activity class on onclick(), this function:

public void down(View v) {
    // ImageManager ob=new ImageManager();
    // ob.DownloadFromUrl("");

     new MyAsnyc().execute();
}

Although I have written the permissions in the manfiest.xml

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

4 Answers4

3

Define these on the top side

Button BtnDownload;

DownloadManager downloadManager;

After, You should write on create inside :

BtnDownload = (Button)findViewById(R.id.button1);

Later, You should write to the button's click event

downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);

Uri uri = Uri.parse("your url");

DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

Long reference = downloadManager.enqueue(request);

Finally, you need to add this onto the application tag to the manifest.xml :

<uses-permission android:name="android.permission.INTERNET"/> 
Prajwal
  • 3
  • 2
  • Please, make sure that you are using code blocks for code examples – Yago Azedias Mar 28 '18 at 12:11
  • Welcome to StackOverflow: if you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar or using Ctrl+K on your keyboard to nicely format and syntax highlight it! – WhatsThePoint Mar 28 '18 at 12:20
3

try this

public class MyAsnyc extends AsyncTask<Void, Void, Void> {
    public static File file;
    InputStream is;

    protected void doInBackground() throws IOException {

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");
        try {    
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            is = ucon.getInputStream();

            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

        } catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute() {
        try {
            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(null,
                    new String[]{file.toString()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
Pierre
  • 8,397
  • 4
  • 64
  • 80
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
1
new DownloadImageFromUrlTask().execute(imagePath);

//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'

public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
        String downloadPath = "";

        @Override
        protected Bitmap doInBackground(String... args) {
            try {
                downloadPath = args[0];
                return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
                String root_Path =  Environment.getExternalStorageDirectory().toString();

                String saveImagePath = root_Path + "/" + photoFileName;

                saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
                loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
            } else {
                myImageView.setImageResource(R.drawable.default_photo);
            }
        }
    }

    public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
        Boolean result = true;
        if (theTempBitmap != null) {
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(theTargetFile);
                theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out);    //kdfsJpegCompressionRatio
            } catch (FileNotFoundException e) {
                result = false;
                e.printStackTrace();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            result = false;
        }
        return result;
    }

    public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
        Glide.with(theCtx)
                .load(theUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(theImageView);

    }
jessica
  • 1,700
  • 1
  • 11
  • 17
-1

The problem with your code is you have not read the InputStream. You should try this

Bitmap bitmap = BitmapFactory.decodeStream(is); 
return bitmap;

and make the Asynctask return type as Bitmap. Or, As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.

Okey.Try this edited Asynctask.

    private  class MyAsnyc extends  AsyncTask <Void,Void,File> {
    File file;
    @Override 
    protected File doInBackground( Void... params ) { 
        InputStream is = null;
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File( path , "Demo Picture.jpg" ) ;  
        try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ; 
            path.mkdirs();

            OutputStream os = new FileOutputStream(file) ; 
            byte [ ] data = new byte [ is.available ( ) ] ;
            is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ; 
            return file;
        }
        catch (Exception e){ 
            Log .d ( "ImageManager " , " Error: " + e ) ;
        }           

        return null;
    }
    protected void onPostExecute (File file) {
        try{
            MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) { 
                Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
        }catch (Exception e) {
            // TODO: handle exception
        }
    }}
Som
  • 1,514
  • 14
  • 21
  • i don't understand what do you mean ? –  Mar 18 '12 at 20:55
  • Try the third parameter of Asynctask as InputStream and return is from doinbackground – Som Mar 18 '12 at 21:02
  • can you modify this code by using the things that you have told cause i come confused !! –  Mar 18 '12 at 21:17
  • see the log ":: 03-18 23:28:24.611: D/ImageManager(332): Error: java.io.FileNotFoundException: /mnt/sdcard/Pictures/DemoPicture.jpg (Permission denied) –  Mar 18 '12 at 21:31
  • please the words appeared separated letters so i can't read the code can you see that ?? –  Mar 19 '12 at 06:15
  • Actually i posted this using my mobile thats why. Ok i will just update it. – Som Mar 19 '12 at 08:18
  • Now it sims gud but still not properly formatted. You do the code formatting and try it out. Hope it helps ! – Som Mar 19 '12 at 08:50