How to create callback (add as dynamic argument, a function)?

TyrionLannister picture TyrionLannister · May 17, 2013 · Viewed 6.9k times · Source

I'm creating this method / function and I need to implement callback. I mean, I need to add as dynamic argument, a function. I have read several articles but I can not understand how to get it. Any idea or example of use?

public void httpReq (final String url, final Object postData, String callbackFunct, Object callbackParam,String callbackFailFunct) {
    if (postData == null || postData == "") {
        //GET
        Thread testGET = new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuilder builder = new StringBuilder();
                HttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                ....
                }
        }
    } else {
        //POST
        Thread testPOST = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpGet httpPost = new HttpPost(url);
                ....
                }
        }
    }
}

Answer

Blackbelt picture Blackbelt · May 17, 2013

Define your interface:

public interface MyInterface {
  public void myMethod();
}

add it as paramter for your method

public void httpReq (final String url, final Object postData, String callbackFunct, Object callbackParam,String callbackFailFunct, MyInterface myInterface) {
    // when the condition happens you can call myInterface.myMethod();
}

when you call your method you will have, for instance,

myObjec.httpReq(url, postData, callbackFunct, callbackParam, callbackFailFunct,
 new MyInterface() {
     @Override
     public void myMethod() {

    }
 });

is that what you need?