How to Download file in internal Storage using Volley in Android Studio?

Viewed 2116

In my android app I want to download a file from web server to Mobile's Internal Storage using Download Manager in android studio. And also i need to use it inside the Volley function.

My Code

button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
  DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
  Uri uri = Uri.parse("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png");
  DownloadManager.Request request = new DownloadManager.Request(uri);
 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);                
  request.setDestinationInExternalFilesDir(DownloadsActivity.this, Environment.DIRECTORY_DOWNLOADS, "banu.jpg");
}

In above code I had tried it in button click.

2 Answers

To download from an URL you need to use the AsyncTask process then save image using Bitmap.

your class...ACTIVITY...{
 oncreateFunction(){
  // your codes...
  button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {

     Uri uri = Uri.parse("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png");
     mTask = new DownloadTask()
                    .execute(new URL(uri));
     }
    });
}

private class DownloadTask extends AsyncTask<URL,Void,Bitmap>{

    protected void onPreExecute(){

        // if need to show progress
    }

    // Background Task/non-UI thread
    protected Bitmap doInBackground(URL...urls){
        URL url = urls[0];
        HttpURLConnection conn= null;

        try{

            conn = (HttpURLConnection) url.openConnection();
            conn.connect();

            InputStream inputStream = conn.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);

            return bmp;

        }catch(IOException e){
            e.printStackTrace();
        }finally{

            conn.disconnect();
        }
        return null;
    }

    protected void onPostExecute(Bitmap result){

        if(result!=null){

            mImageView.setImageBitmap(result);
            Uri imageInternalUri = saveImageToInternalStorage(result);              
            mImageViewInternal.setImageURI(imageInternalUri);
        }else {

            // show error if any
        }
    }
 }

 protected Uri saveImageToInternalStorage(Bitmap bitmap){

    ContextWrapper wrapper = new ContextWrapper(getApplicationContext());

    File file = wrapper.getDir("Images",MODE_PRIVATE);

    file = new File(file, "yourFileUnique"+".jpg");

    try{
        OutputStream stream = null;
        stream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
        stream.flush();
        stream.close();

     }catch (IOException e) // Catch the exception
     {
        e.printStackTrace();
     }
     Uri savedImageURI = Uri.parse(file.getAbsolutePath());
     return savedImageURI;
  }

 }

NetworkImageView automatically loads image from background queue and cancel request.

ImageLoader use for detached view and automatically uses memory from disk cache.

we can use NetworkImageView for volley downloading image. Belows are example.

layout_example.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"        
    tools:context=".MainActivity">

    <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/photo"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</RelativeLayout>

and in your MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_example);
    NetworkImageView nv = (NetworkImageView) findViewById(R.id.photo);
    // image for loading...
    nv.setDefaultImageResId(R.drawable.default_image); 
    //ImgController from your code.
    nv.setImageUrl(imageUrl, ImgController.getInstance().getImageLoader()); 
}

Edit

  • with Volley supports the download of strings, images and JSON.

Volley is not suitable for large downloads or streaming (Volley holds all responses in memory during parsing,So large downloads will use a lot of memory).

You should use the DownloadManager for large downloads.

Downloading images

There are two ways of doing this with Volley:

  • ImageRequest – this gets an image at a URL, returning a Bitmap. You can set the required size. Volley does the processing off the main thread

  • ImageLoader – this loads and caches images from remote Url’s. It’s like a manager of multiple ImageRequest’s. It’s ideal for loading images into lists and grids. You can include a memory cache

and Our special image view through NetworkImageView.

For more information it'll help you :https://mobikul.com/downloading-files-using-volley/

I hope it'll help you...!

Related