AQuery AJAX Callback

I believe you folks got to know how easy it is to write Android code when AQuery library is used from my previous posts.

Introduction to AQuery – Android Query
AQuery Button Listener.

It’s time to explore the other most wonderful feature of AQuery and that is ‘Asynchronous Network Calls’. In this post we will be developing simple application to demonstrate how to download Mp3 file from Internet and play it as soon as it is downloaded. I already wrote a separate article [Android AsyncTask Example] on how to make Asynchronous calls to download file from Network but AsyncTask was used rather than AQuery library to perform Asynchronous download.

Steps to download File from Network using AQuery library

  1. Declare a Java String object for http URL
    String url = "";
  2. Specify the target location in mobile SD card where the downloaded file to be stored
    File ext = Environment.getExternalStorageDirectory();
    File target = new File(ext, "pgfolder/jai_ho.mp3");
  3. Initialize progress dialog bar settings:
    ProgressDialogprgDialog = new ProgressDialog(this);
    prgDialog.setMessage("Downloading MP3 from Internet. Please wait...");
  4. Display progress bar by invoking progress( ) method:

    Note that displaying and dismissing progress bar will be taken by AQuery library.

  5. Perform method chaining with progress( ) method and download File from Internet by invoking download( ) method
    aq.progress(prgDialog).download(url, target, new AjaxCallback<File>() {
    		public void callback(String url, File file, AjaxStatus status) {
    			if (file != null) {
    			} else {
    				Toast.makeText(aq.getContext(), "Error occured: Status" + status,
  6. Syntax of download( ) method:

    download(url, target the file to be saved, callback to be called when done);

It would be helpful for you if you take a look at AQuery AJAX Documentation to understand the list of supported methods in AQuery to perform http network calls.

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Application Project] with project name AQueryAJAXDownload
  • Choose Build SDK and minimum required SDK [I chose version 4.1 and 2.2]
  • Enter package name as ‘com.prgguru.example’
  • Click next and select BlankActivity
  • Click next and provide Activity name and Layout name as ‘AQueryAJAXDownload’ and ‘main’ respectively.

Code Listings

Open main.xml, now you can view the layout as either XML or in graphical view and just replace the XML with below one:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="@string/btn_title" />

Open and replace it with below code. Each line is added with comment and I hope it is self understandable. If you still have any doubt/question, discuss it right away in the comment section.

package com.prgguru.example;


import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;

public class AQueryAJAXDownload extends Activity {
	// AQuery object
	AQuery aq;
	// Progress Dialog Bar
	ProgressDialog prgDialog;
	// Mp3 File location
	String url = "";
	// Media player object
	public MediaPlayer mPlayer;

	public void onCreate(Bundle savedInstanceState) {
		// Instantiate AQuery object
		aq = new AQuery(this);
		// Look for button click event using AQuery clicked() method, "downloadSongandPlay");

	// AQuery button click callback method
	public void downloadSongandPlay(View v) {
		// Mp3 file location in SD card
		File file = new File(Environment.getExternalStorageDirectory().getPath()+"/pgfolder/jai_ho.mp3");
		// Get SD card location
		File ext = Environment.getExternalStorageDirectory();
		// Target location where downloaded file to be stored
		File target = new File(ext, "pgfolder/jai_ho.mp3");

		// Disable button in order to avoid multiple button hits;
		// When Mp3 File exists under SD card
		if (file.exists()) {
			Toast.makeText(getApplicationContext(), "File already exist under SD card, playing Music", Toast.LENGTH_LONG).show();
			// Play Music
		// If the Music File doesn't exist in SD card (Not yet downloaded)
		} else {
			Toast.makeText(getApplicationContext(), "File doesn't exist under SD Card, downloading Mp3 from Internet", Toast.LENGTH_LONG).show();
			prgDialog = new ProgressDialog(this); // Instantiate Progress Dialog Bar
			prgDialog.setMessage("Downloading MP3 from Internet. Please wait..."); // Set Progress Dialog Bar message
			prgDialog.setMax(100); // Progress Bar max limit
			prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // Progress Bar style
			prgDialog.setCancelable(false); // Progress Bar cannot be cancelable
			// Display progress dialog bar and initiate download of Mp3 file
			aq.progress(prgDialog).download(url, target, new AjaxCallback<File>() {
				// Once download is complete
				public void callback(String url, File file, AjaxStatus status) {
					// If file does exist
					if (file != null) {
					// If file doesn't exist display error message
					} else {
						Toast.makeText(aq.getContext(), "Error occured: Status" + status,

	protected void playMusic(){
		// Read Mp3 file present under SD card
		Uri myUri1 = Uri.parse("file:///sdcard/pgfolder/jai_ho.mp3");
		mPlayer  = new MediaPlayer();
		try {
				mPlayer.setDataSource(aq.getContext(), myUri1);
				// Start playing the Music file
				mPlayer.setOnCompletionListener(new OnCompletionListener() {
					public void onCompletion(MediaPlayer mp) {
						// TODO Auto-generated method stub
						// Once Music is completed playing, enable the button;
						Toast.makeText(getApplicationContext(), "Music completed playing",Toast.LENGTH_LONG).show();
		} catch (IllegalArgumentException e) {
			Toast.makeText(getApplicationContext(), "You might not set the URI correctly!",	Toast.LENGTH_LONG).show();
		} catch (SecurityException e) {
			Toast.makeText(getApplicationContext(),	"URI cannot be accessed, permissed needed",	Toast.LENGTH_LONG).show();
		} catch (IllegalStateException e) {
			Toast.makeText(getApplicationContext(),	"Media Player is not in correct state",	Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			Toast.makeText(getApplicationContext(),	"IO Error occured",	Toast.LENGTH_LONG).show();

Include AQuery.jar
Download AQuery jar from here and place it under lib folder.

AndroidManifest.xml permission

Don’t forget to add write and internet permissions in AndroidManifest.xml:

    <!-- Permission: Allow application to connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission: Allow application to write to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Create Folder under SD card
Make sure you have created folder named ‘pgfolder’ under SD card in which the downloaded Mp3 file will be saved.



That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android  is the installation file similar to exe in windows.


If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

You are always welcome to provide your comments and feedback from comment box.


AQuery documentation

Related Articles

Author: Udhay

Share This Post On
468 ad
Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest