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);
                ....
                }
        }
    }
}
2
  • This code already scares me. Hopefully you're just using it for your post here. Commented May 17, 2013 at 16:24
  • +1 on the GoT username and routing for the little guy Commented May 17, 2013 at 16:25

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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!
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.