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 = "http://programmerguru.com/android-tutorial/wp-content/uploads/2014/01/jai_ho.mp3";
  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...");
    prgDialog.setIndeterminate(false);
    prgDialog.setMax(100);		
    prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    prgDialog.setCancelable(false);
  4. Display progress bar by invoking progress( ) method:
    aq.progress(prgDialog);

    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) {
    				playMusic();
    			} else {
    				Toast.makeText(aq.getContext(), "Error occured: Status" + status,
    								Toast.LENGTH_SHORT).show();
    			}
    		}
    	});
  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="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:text="@string/btn_title" />

</LinearLayout>

AQueryAJAXDownload.java
Open AQueryAJAXDownload.java 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 java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
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 = "http://programmerguru.com/android-tutorial/wp-content/uploads/2014/01/jai_ho.mp3";
	// Media player object
	public MediaPlayer mPlayer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// Instantiate AQuery object
		aq = new AQuery(this);
		// Look for button click event using AQuery clicked() method
		aq.id(R.id.btnProgressBar).clicked(this, "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
		aq.id(R.id.btnProgressBar).enabled(false);
		// 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
			playMusic();
		// 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.setIndeterminate(false);  
			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) {
						playMusic();
					// If file doesn't exist display error message
					} else {
						Toast.makeText(aq.getContext(), "Error occured: Status" + status,
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
	}

	protected void playMusic(){
		// Read Mp3 file present under SD card
		Uri myUri1 = Uri.parse("file:///sdcard/pgfolder/jai_ho.mp3");
		mPlayer  = new MediaPlayer();
		mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try {
				mPlayer.setDataSource(aq.getContext(), myUri1);
				mPlayer.prepare();
				// Start playing the Music file
				mPlayer.start();
				mPlayer.setOnCompletionListener(new OnCompletionListener() {
					public void onCompletion(MediaPlayer mp) {
						// TODO Auto-generated method stub
						// Once Music is completed playing, enable the button
						aq.id(R.id.btnProgressBar).enabled(true);
						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.

[pglinkadssmall1]

Demo

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.

[pglinkadssmall]

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.

Reference

AQuery documentation
[pgwriteforus]
[pgfeedback]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Ariel

    hi sir i got an error in downloading the mp3? it say com.androidquery.callback.AjaxStatus@b2ff2440

    • Hi Ariel,

      Please understand that using AJAX we can download only the files in the below format:

      1. Plain text
      2. HTML
      3. JSON
      4. XML

      We cannot download media files using AJAX. In case if you want to download Mp3 file, download the hyperlink of Mp3 file using AJAX and play it in the Application.

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

Shares