Android AsyncTask – Download Image/Bitmap

Android AsyncTask – Download Image/Bitmap







Android AsyncTask Download Image/Bitmap

There are plenty of image downloader libraries.Picasso and Glide are so far my best two.However,the truth is they are third party libraries and have to be added as a dependency in android studio or jar in Eclipse.When I was writing this example some time ago I was using Eclipse ADT.Its still a massively fast and I do prefer doing these types of examples with it.However, I hate the process of downloading a jar and addding to Eclipse.So In this tutorial we talk Android AsyncTask and Bitmaps.How to download image and show it in a simple gridview.

Cheers.

 

 

Section 1 : Our MainActivity Class

  • Launcher activity
  • Download image on button click as a bitmap.
  • Show it in an imageview.
package com.tutorials.asyncimagedownload;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
  private String url="http://10.0.2.2/galacticnews/wp-content/uploads/2016/06/spacecraft.jpg";
  ImageView img;
  Button downloadBtn;
  ProgressDialog pd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img=(ImageView) findViewById(R.id.imageView1);
        downloadBtn=(Button) findViewById(R.id.button);
        downloadBtn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
        // TODO Auto-generated method stub
        new Downloader().execute(url);
      }
    });
    }
    private class Downloader extends AsyncTask<String,Void,Bitmap>
    {
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    		//CREATE PD,SET PROPERTIES
    		pd=new ProgressDialog(MainActivity.this);
    		pd.setTitle("Image Downloader");
    		pd.setMessage("Downloading...");
    		pd.setIndeterminate(false);
    		pd.show();
    	}
    @Override
    protected Bitmap doInBackground(String... url) {
      // TODO Auto-generated method stub
      String myurl=url[0];
      Bitmap bm=null;
      InputStream is=null;
      try
      {
        is=new URL(myurl).openStream();
        //DECODE
        bm=BitmapFactory.decodeStream(is);
      }
      catch(Exception e)
      {
        e.printStackTrace();
      }
      return bm;
    }
    @Override
    protected void onPostExecute(Bitmap result) {
      // TODO Auto-generated method stub
      super.onPostExecute(result);
      //SET TO IMG
      img.setImageBitmap(result);
       //DISMISS
      pd.dismiss();
    }
    }
}

 

Android Manifest

  • Add Internet permission to androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.asyncimagedownload"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.tutorials.asyncimagedownload.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.asyncimagedownload"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.tutorials.asyncimagedownload.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

 

Layout

  • Add ImageView and button to your xml layout.
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="#009968"
        android:layout_marginBottom="58dp"
        android:text="Download" />
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="43dp"
        android:src="@drawable/imageloading" />
</RelativeLayout>

 

Android Image downloaded via AsyncTask

Android Image downloaded via AsyncTask

 

 

 



    COMMENTS