Android Download Image with Progress Dialog Example

On February 12, 2014, in Android, by James Liu

This is the session 2 of Android Wallpaper App tutorial. In last tutorial, we talked about how to use android gridview to show a list of wallpaper thumbnails. In this tutorial, I will show you how to download a image with a progress dialog. In this wallpaper app example, I already get a list of available wallpaper images. When I click any of thumbnail images, it will start to download the real image from internet and show a progress dialog to trace the downloading progress. Here is screenshot about the final result. You can also download the source code for free and run this example on your own android phones or tablets.

This Android Wallpaper App example includes four tutorials:

Add Progress Dialog in Android App

First of all, I will add a progress dialog in the onCreate function. The following code will initialize the dialogue by setting the ProgressDialog title, ProgressDialog message and style. Later, we will show the dialog and set its progress when user clicks on images in gridview. Here is the source code example:

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		//grid view
		GridView gridView = (GridView) findViewById(R.id.gridView1);
		gridView.setAdapter(new ImageAdapter(this));
		gridView.setOnItemClickListener(gridViewImageClickListener);
		
		//progress bar
		downloadProgressDialog = new ProgressDialog(MainActivity.this);
		downloadProgressDialog.setTitle("Downloading Wallpaper");
		downloadProgressDialog.setMessage("Downloading in progress...");
		downloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downloadProgressDialog.setProgress(0);
		//downloadProgressDialog.setMax(20);
		//downloadProgressDialog.show();
	}

Add Item Click Listener on GridView

In the second step, I will add an item click listener on the gridview which we created in last tutorial. Inside the listener, I will show the progress dialog and start an asynctask to download the real image.

	private OnItemClickListener gridViewImageClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			downloadProgressDialog.show();
			new DownloadWallpaperTask().execute(imageURLArray[arg2]);
		}
	};

Download Images with AsyncTask

In the third step, I will create an AsyncTask subclass DownloadWallpaperTask, which will handle the downloading image job, and update the download progress. After the download job finishes, I will hide the download progress dialog and show the whole image in a full size in a new Activity. Please keep in mine, the class DownloadWallpaperTask is an inner class. Here is the source code of this class. If you just want to find a piece of code to download a image, you can also check Download Images by AsyncTask.

private class DownloadWallpaperTask extends AsyncTask <String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        String wallpaperURLStr = params[0];
        String localPath = Integer.toString(wallpaperURLStr.hashCode());
        try {
            URL wallpaperURL = new URL(wallpaperURLStr);
            URLConnection connection = wallpaperURL.openConnection();
            
            //get file length
            int filesize = connection.getContentLength();
            if(filesize < 0) { //comment >
                downloadProgressDialog.setMax(1000000);
            } else {
                downloadProgressDialog.setMax(filesize);
            }
            
            InputStream inputStream = new BufferedInputStream(wallpaperURL.openStream(), 10240);
            String appName = getResources().getString(R.string.app_name);
            OutputStream outputStream = openFileOutput(localPath, Context.MODE_PRIVATE);
            byte buffer[] = new byte[1024];
            int dataSize;
            int loadedSize = 0;
            while ((dataSize = inputStream.read(buffer)) != -1) {
                loadedSize += dataSize;
                publishProgress(loadedSize);
                outputStream.write(buffer, 0, dataSize);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return localPath;
    }

    protected void onProgressUpdate(Integer... progress) {
        downloadProgressDialog.setProgress(progress[0]);
    }
    
    protected void onPostExecute(String result) {
        downloadProgressDialog.hide();
        
        //open preview activity
        Bundle postInfo = new Bundle();
        postInfo.putString("localpath", result);

        if (previewPanelIntent == null) {
            previewPanelIntent = new Intent(MainActivity.this,
                    PreviewPanel.class);
        }

        previewPanelIntent.putExtras(postInfo);
        startActivity(previewPanelIntent);
    }

}

Debug Tips

Some people have problems about getting image length from server. When they are using following code to get the image size, getContentLength returns -1 or a negative value.

int filesize = connection.getContentLength();

That is because the server which hosts your images is not setting a “Content-Length” header in the http response message. That’s a server problem. So in my approach, I am setting a number 1000000, which means the default file size is 1M.

download an image with progress dialog

Try Example Android App

You can download and install this android app by click the following link, or scan the following QR code to download and install on your android phone simply. If you feel it is helpful, please support me by clicking the banner inside the app.
Download and Run This Example on Your Android Phone

chart

Get Full Source Code under $3.99


You will get whole source code at $3.99. It is fully functional, and embedded the Google AdMob module by default. With this source code, you can do everything you want:

  • Load your own images;
  • Monetize the app with your own AdMob publish id;
  • Use the source code in your own project;
  • Publish this app with your Google Play account;
 

9 Responses to “Android Download Image with Progress Dialog Example”

  1. Robert says:

    How can we download wallpaper that can set wallpaper? Thanks

    • James says:

      Hello Robert,

      I have finished my tutorial yet. But here is the short answer:

      WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
      try {
      wallpaperManager.setBitmap(imageBitmap);
      } catch (IOException e) {
      e.printStackTrace();
      }

      In next tutorial, I will cover this topic.

  2. Kenny says:

    In this section:
    if (previewPanelIntent == null) {
    previewPanelIntent = new Intent(MainActivity.this,
    PreviewPanel.class);
    }
    Can u explain me what PreviewPanel class and its content?
    Thanks alot!

  3. Fire says:

    Hi James,

    Can I know how can I have all the wallpapers in the apps instead of downloading it from Internet?

    Thanks

  4. budi says:

    Yeah very happy found this tutorial…
    I am newbie learning dev android..
    I try tomorow in my project..
    Thanks james..

  5. UmanHJ says:

    Can you please Show us the Preview_Panel_Intent ?
    Its missing from your code

Leave a Reply

WordPress主题

Free WordPress Themes