Create callback function in Android

In Android, you have to write lots of code for some actions. To reduce lines of code we use functions and classes to reuse the code but sometimes we need the callback of function. So here I will tell how to create the callback with an example. 

Let take an example in Android, in most places we need a confirm dialog to confirm any action like delete the record, leave the page etc. The traditional way to do it create a confirm dialog and write code of confirm dialog positive callback. But this might take 13-15 lines to write the code. See the code snippet below:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext,R.style.confirmdialog);
alertDialog.setTitle("Perform some action");
alertDialog.setMessage("Are you sure to perform this action?");
alertDialog.setPositiveButton("Yes",
     new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
                  // Your Action Code Here
             }
         });

// on cancel button
alertDialog.setNegativeButton("Cancel",
     new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
             }
         });
// Showing Alert Dialog
alertDialog.show();

Here you can see 15 lines of code required to confirm an action. Now we will create a function in our MyHelper class to confirm an action and this function will be reusable anywhere in the whole application. 

public class MyHelper {
	private Context mContext;

	public MyHelper(Context context) {
        this.mContext = context;   
        pDialog=new ProgressDialog(context);
    }

	public interface MyCallback {
		void callbackCall();
	}
    public void confirmDialog(String title, String content, String actionLabel, final MyCallback callback){
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext,R.style.confirmdialog);
		alertDialog.setTitle(title);
		alertDialog.setMessage(content);
		alertDialog.setPositiveButton(actionLabel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						callback.callbackCall();
					}
				});
		// on pressing cancel button
		alertDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		// Showing Alert Message
		alertDialog.show();
	}
}

In the above class, we have created the confirmDialog function that has a callback. The callback will be trigger when the user clicks on the confirm button.

In Android, we need Interface to create the callback. In our Example, we have created MyCallback Interface that has one method callbackCall. In the function confirmDialog we passed the callback object in the last and call the callback object's function on Dialog button press:  callback.callbackCall(); .

Now we will use this function in our activity as below:

public class MyActivity extends AppCompatActivity {
    MyHelper helper;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        helper = new MyHelper(this);
        v.findViewById(R.id.btnDelete).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   deleteRecord();
               }
          });
    }

    public void deleteRecord(){
        helper.confirmDialog("Delete Record", "Are you sure to delete?", "Delete" , new MyHelper.MyCallback() {
            @Override
            public void callbackCall() {
                 // Your Action Code Here
            }
        });
    }
}

As you can see here to confirm the action we need to write only 4 lines of code. confirmDialog function has the callback where you can write your code for your action.

 

 

 

 

Keywords: