Image download from server Android code

Image download from server Android code will enable download bitmap image for given url. Below is Android code which will download a bitmap image from Url and set it to image view. Here we have defined a constructor to receive the call back from AsyncTask.

public class DownloadImagesTask extends AsyncTask<URL, Void, Bitmap> {

    String TAG = "DownloadImagesTask";
    private final DownloadTaskListner listener;
    private final ImageView iv;

    public DownloadImagesTask(DownloadTaskListner listner, ImageView iv) {
        this.listener = listner;
        this.iv = iv;
    }

    @Override
    protected Bitmap doInBackground(URL... urls) {
        Log.i(TAG, String.valueOf(urls[0]));
        URL url = urls[0];
        HttpURLConnection connection = null;
        try{
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
            return bmp;
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            connection.disconnect();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if(bitmap!=null) {
                listener.onDownloadComplete(bitmap, iv);
    }
}

public interface DownloadTaskListner {
    void onDownloadComplete(Bitmap bitmap, ImageView iv);
    void onDownloadError(String error);
}
public class OrderSummaryActivity extends AppCompatActivity implements DownloadTaskListner{

    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = findViewByID(R.id.imageView)
        DownloadImagesTask task = new DownloadImagesTask(this, image);
     task.execute(stringToURL("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"));

}

    @Override
    public void onDownloadComplete(Bitmap bitmap, ImageView iv) {
        iv.setImageBitmap(bitmap);
    }

    @Override
    public void onDownloadError(String error) {

    }

    public static URL stringToURL(String urlString){
        try{
            URL url = new URL(urlString);
            return url;
        }catch(MalformedURLException e){
            e.printStackTrace();
        }
        return null;
    }

}

Image download from server Android code.

Also check : http://www.unbounded.in/image-upload-to-php-server-from-android-code/

(Visited 100 times, 1 visits today)

1 thought on “Image download from server Android code”

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
12 ⁄ 3 =