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);
}
}
}
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With