Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing method callback in Android

Currently in my project, I am making Http requests and I want different http response to be sent to different callback methods.

I wrote a quick sample below to show what I want to do. I know it probably wont be possible the way i want it, but are there any clean solutions to achieve the same thing?

Sample:

Activity Class:

public class Main extends Activity{  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Services service = new Services();
        service.login("user", "password", **onLoginComplete()** );
    }

    public void onLoginComplete(String HTTPResponse){
        // Do something with the response
    }
}

Service Class:

public class Services{  

    public void login(String user, String password, CALLBACK){
        Request request = createLoginRequest(user, password);
        sendRequest(request, CALLBACK);
    }

    public class sendRequest extends AsyncTask{
        @Override
        protected Object doInBackground(Object... params) {
             // Do Http Request
             // Get Response
             CALLBACK(response);
        } 
    }
}
like image 584
AlexCheuk Avatar asked Sep 13 '12 23:09

AlexCheuk


1 Answers

interface OnLoginCompleteListener {
    void onLoginComplete(String response);
}

And then

public void login(String user, String password, OnLoginComplete listener) {
    mOnCompleteListener = listener;
}

and

protected Object doInBackground(Object... params) {
    mOnCompleteListener.onLoginComplete(response);
}

and finally

service.login("user", "password", new OnLoginCompleteListener() {
    public void onLoginComplete(String response) {
        // Handle your response
    }
});
like image 199
Volodymyr Lykhonis Avatar answered Oct 02 '22 02:10

Volodymyr Lykhonis