Using callbacks in Java and android

Javascript is kind of a propagator of Callbacks concept, as functions being first class objects in javascript. You can implement callbacks in Java too using interface concepts.

What are callbacks? As name suggests, these are the functions which needs to be called back after some event, lets say, after you read data from database, or it could be as simple as touch events on the screen. Callbacks are very powerfull as these are event based, allowing for non-blocking, event driven programming. To understand more about event driven programming, gothrough this blog.

Syntax to define a callback I am working on this android app (hence the name of the blog includes "android" :P), which requires to download image from the server and load that image on to the view (it is bit complicated than that, for this simple scenario you can use Picasso library).

So I have created an interface called CallBackForTeams as below :

public interface CallBackForTeams {

    public void afterLogoDownload();

On some event, let's say, on download complete, I am triggering afterLogoDownload() method as below

public void triggerDownload(Uri uri, CallBackForTeams callBackForTeams){
  CallBackForTeams callback=callBackForTeams;

  /*Some code which performs download, call below method on download compleation*/


Where callBackForTeams is passed by a calling function as an argument, which gets triggered after download compleation.

Code in calling function looks like this, objectTeamsHelper is a ObjectTeamsHelper class instance, which has "triggerDownload" as its method. uri is an instance of Uri, which is defined before calling this function.

objectTeamsHelper.triggerDownload(uri,,new CallBackForTeams(){

                                public void afterLogoDownload() {

  //write some custom code which does some thing with the information , that downloading completed.

This is one way of implementing callbacks in android, let me know in below comments section, if you have any other method to implement callback.