Download Image using AsyncTask Tutorial in Android
Android Sample Codes Uncategorized

Download Image using AsyncTask Tutorial in Android

Tutorial on Download Image using AsyncTask Tutorial in Android , you will learn how to download an image using URL address into your Android application.

In the layout design, button click will start an AsyncTask class to begin downloading an image from a URL address specified in the Edittext control in your android application .

Download Image using AsyncTask Tutorial in Android [Step By Step]

AsyncTask class is used to do background operations that will update the UI(user interface). Mainly we used it for a few seconds at the most that will not effect on our main thread.

In Android, AsyncTask (Asynchronous Task) allows us perform operations in the background and then synchronize again with our main thread.

AsyncTask class is firstly executed using execute() method. The execute() method calls onPreExecute() method then onPreExecute()method calls doInBackground()method for background processes and then doInBackground() method calls onPostExecute() method to update the UI.

Download Image using AsyncTask Tutorial in Android

Understanding Android AsyncTask

Async task enables you to implement MultiThreading concept in android. AsyncTask allows us to performing background tasks and passing the results to the UI thread (main thread).

Generic Types in AsyncTask

    • Params − type of parameters used for execution.
    • Progress – progress of the operation. While doing background operation we can update information on UI thread using onProgressUpdate() method.
    • Result –results of the background operation.

AsyncTask goes through 4 steps:

    • onPreExecute() Invoked on the UI thread before the operation is executed. We can define code, which need to be executed before background operation starts executing.
    • doInBackground have code which needs to be executed in background. Using doInBackground() we can send results to multiple times to event UI thread by calling  publishProgress() method, to notify background .
    • onProgressUpdate() method receives progress updates from doInBackground() method, which is published via publishProgress() method. This method is used to display any form of progress in the user interface while the background computation is still executing.
    • onPostExecute() receives results from the  doInBackground() method.
    • An running async task can be cancelled by calling cancel(boolean) method.

Create a new project in android studio  File > New Project> Empty Activity. Fill in the details and name your project AsyncTaskImageDownload.

Open your MainActivity.java and paste the following code.

MainActivity.java
package com.example.asynctaskimagedownload;
import java.io.InputStream;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {

public String URL="";
EditText editText;
ImageView image;
Button button;
ProgressDialog mProgressDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the layout from image.xml
setContentView(R.layout.activity_main);

editText=(EditText)findViewById(R.id.edittxt);

// Locate the ImageView in activity_main.xml
image = (ImageView) findViewById(R.id.image);

// Locate the Button in activity_main.xml
button = (Button) findViewById(R.id.button);

// Capture button click
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {

//get the image url from the text box
URL=editText.getText().toString();

// Execute DownloadImage AsyncTask
new DownloadImage().execute(URL);
}
});
}

// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Download Image Using AsyncTask Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Downloading...please wait...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}

@Override
protected Bitmap doInBackground(String... URL) {

String imageURL = URL[0];

Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}

@Override
protected void onPostExecute(Bitmap result) {
// Set the bitmap into ImageView
image.setImageBitmap(result);
// Close progressdialog
mProgressDialog.dismiss();
}
}
}

In this activity, I have created a reference to EditText, Button and an ImageView and on button click will show a progress dialog and start the Image download using URL address specified in the EditText control (copy and paste any image URL address from the internet in the EditText control) using AsyncTask class. The download image will be set into an ImageView.

Next, create an XML layout file for your MainActivity.

Paste the following code in the activity_main.xml file in your res >layout> activity_main folder.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/edittxt"
android:hint="Copy paste your image location"
/>

<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:text="Click Here To Download Image"
android:paddingBottom="50dp"
android:gravity="center"/>
<ImageView
android:id="@+id/image"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
/>
</LinearLayout>

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.

strings.xml
<resources>
<string name="app_name">AsyncTaskImageDownload</string>
<string name="menu_settings">Settings</string>
<string name="button">Download Image</string>
</resources>

In your AndroidManifest.xml, we need to declare a permission to connect to the Internet. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asynctaskimagedownload">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="27" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Output :

 

Download Image using AsyncTask Tutorial in Android

Leave a Reply

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