[:en]Android: AsynTask download image[:]

[:en]AsynTask download image

Step 1: activity_mail.xml



    

Step 2. MainActivity.java

package com.example.cambridge.asynctaskdownloadimage;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    Button button;
    ImageView imageView;
    String image_url = "http://inventlinks.com/wp-content/uploads/2015/12/20150426_142344_7_bestshot.jpg";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        imageView = (ImageView)findViewById(R.id.image_view);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               // Set object
               DownloadTask downloadTask = new DownloadTask();
               downloadTask.execute(image_url);


            }
        });

    }

   class DownloadTask extends AsyncTask{
       ProgressDialog progressDialog;


       @Override
       protected void onPreExecute() {
           progressDialog = new ProgressDialog(MainActivity.this);
           progressDialog.setTitle("Download in progress...");
           progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
           progressDialog.setMax(100);
           progressDialog.setProgress(0);
           progressDialog.show();


       }

       @Override
       protected String doInBackground(String... params) {
           String path = params[0];
           int file_lenght = 0;

           try {
               URL url = new URL(path);
               URLConnection urlConnection = url.openConnection();
               urlConnection.connect();
               file_lenght =  urlConnection.getContentLength();
               File new_folder = new File("sdcard/photoalbum");
               if(!new_folder.exists()){
                   new_folder.mkdir();
               }
               // Insert file
               File input_file = new File(new_folder,"downloaded_image.jpg");
               InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
               byte[] data = new byte[1024];
               int total = 0;
               int count = 0;
               // Read file
               OutputStream outputStream = new FileOutputStream(input_file);
               // Write the outpout
               while ((count=inputStream.read(data))!=-1){
               // update total
                   total+= count;
                   outputStream.write(data,0,count);
                   int prograss = (int)total*100/file_lenght;
                   publishProgress(prograss);
               }
               inputStream.close();
               outputStream.close();


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

           return "Download completed...";
       }

       @Override
       protected void onProgressUpdate(Integer... values) {
          // Update progressBar status
           progressDialog.setProgress(values[0]);
       }

       @Override
       protected void onPostExecute(String result) {
           progressDialog.hide();
           Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
           String path = "sdcard/photoalbu/downloaded_image.jpg";
           imageView.setImageDrawable(Drawable.createFromPath(path));

       }
   }


}

Step 3. Manifest.xml




    // Must get this permission for Internet and  external storage
    
    

    
        
            
                

                
            
        
    



[:]

Print Friendly, PDF & Email
Scroll to Top