Android Simple callBack

Michael Tran (mytee)
2 min readMar 31, 2019

Static callBack structure

1- Create a global interface file, say myCallBackInterface.java with content like this:

package com.yourPackage

//define callback interface
public interface MyCallbackInterface {
public abstract void onDownloadFinished(String result);
}

Note that the abstract method means this has to be overridden.

2- Define the callBack func in your Main activity, say like this:

MyCallbackInterface callback = new MyCallbackInterface() {
@Override
public void onDownloadFinished(String result) {// … your code here. ie. handle the result like process the string result …} }

3- Define your function that uses callback like

public static void postData(String targetUrl, HashMap<String, String> paramsPost, final MyCallbackInterface callback) {
..new HttpRequest() {
@Override
public void onResponse(String response) {
super.onResponse(response);
callback(response); }
.....
}

So the data returns in response to post call will be sent to the callback and got parsed to json or processed in other ways. This is typical callback and it works. Dont try to make wrapper classes, no need for them. The suggestions and samples in stackoverflow are … mmm… overskilled?

You can of course use callback as closure like in Swift. You can skip step 2 to form a closure like this

postData("https://mydomain", myHashmap, new MyCallbackInterface {
@Override
public void onDownloadFinished(String result) {// … your code here. ie. handle the result like process the string result …} }
});

I would prefer step 2 as it is clearer to read and debug but it is not wrong to use closure format.

Why use callBack instead of listener? 2 reasons:

  1. Maintenance: The function to process data is independent to the module that produces data. ie. process data returned from a Rest call. This makes the code easy to read and clear logic.
  2. Standard: It is typical async architect and structure. The code can be translated to other languages. Listener is Android only.

--

--