Rafi Rafi - 5 months ago 27
Java Question

Android - Java Equivalent Of iOS Block Callbacks?

In my Android app, I'd like to implement success and error callbacks for when I get reading passages from my backend. In iOS, it would look like this:

In my Passage.h:

-(void)getPassagesWithSuccessCallback:(void (^)(NSArray<Passage *> *))success errorCallback:(void (^)(NSString *))errorString;

In my Passage.m:

-(void)getPassagesWithSuccessCallback:(void (^)(NSArray<Passage *> *))success errorCallback:(void (^)(NSString *))errorString {
MyApiInterface* api = [MyApiInterface sharedInstance];
[api sendGetRequestTo:@"passages" successCallback:[Passage modelListCallback:success] errorCallback:error];

In my Android app, I'm using
to handle my API requests, but I want to further encapsulate this API interfacing by having a Passage.java class with a
public static void
method that gets the passages. Something like this:

public static void getPassagesForFirebaseUser(FirebaseUser user, Context context) {
final String url = URL_BASE + "/passages.json" + "?auth=" + user.getToken(false);
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
// convert JSON into ArrayList<Passage> object
// pass on this array of Passages in the success completion listener of the method that called this
// just like iOS does success(passages)
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
// convert error to string
// pass on this errorString in the error completion listener of the method that called this
// just like iOS does error(errorString)

Is there any way to get this kind of implementation flow?


You can use an Interface

public interface ICallbacks { 
    public void onResponse(JSONObject response);
    public void onError(VolleyError error);

Then in your routine code just put a new instance of Callbacks (depending on ide that you work could autogenerate the methods)

public static void getPassagesForFirebaseUser(FirebaseUser user,
Context context, ICallbacks events) { 
//here code and call ICallbacks methods
if(result){ events.onResponse(response); }
if(error){ events.onError(err); }

ultimately you can call the method with :

getPassagesForFirebaseUser(user, context, new ICallbacks(){
    public void onResponse(JSONObject response){
        //Success !!!
    public void onError(VolleyError response){
        //Error !!!

Sorry for my English, hope this help !