3

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);
                ....
                }
        }
    }
}
svick
  • 236,525
  • 50
  • 385
  • 514
TyrionLannister
  • 103
  • 1
  • 3
  • 7

1 Answers1

15

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?

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • Thank you very much! Now I understand how to use it. @ChristianBongiorno Why scares you the code? Is for having pointed "callbackFunct String, Object callbackParam, String callbackFailFunct"? Greetings! – TyrionLannister May 17 '13 at 17:31
  • You have nearly identical Thread code and you have declared them as anonymous inner classes (hence the reason you need to declare your function parameters as 'final' If you must do multi threading you should create discrete static inner classes (not anonymous) and They should be 'Callable' s so you can submit them to the Executor service. Oh yeah, and you code here doesn't actually START the threads. I guess the whole use of threads at all without a clear reason why is my concern – Christian Bongiorno May 18 '13 at 00:00
  • Thanks, that's exactly what i also needed. – Adrian Olar May 15 '14 at 09:53