Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to make http calls in android

So i need to make a couple of http calls which return JSON responses containing a single or an array of json objects. i have the whole part of the actuall http client call made and working which returns a string with the json response.

So my question is this: What is the best way to make the calls async. i am currently using a async task that calls the method which returns the string in the background method and parses the string via another call to a static method used for parsing which returns a POJO containing all the data which i send to the postExecute part where i present the results to ui based on the outcome. Is this a good practice or is there a better method?

I was thinking of maybe introducing interfaces to provide the data for example a onSuccess listener and onFail Listener. so any suggestions on this?

thank you.

like image 349
DArkO Avatar asked Feb 24 '11 17:02

DArkO


3 Answers

So my question is this: What is the best way to make the calls async. i am currently using a async task that calls the method which returns the string in the background method and parses the string via another call to a static method used for parsing which returns a POJO containing all the data which i send to the postExecute part where i present the results to ui based on the outcome. Is this a good practice or is there a better method?

IMO, if AsyncTask suits your needs, you should use it--it was created specifically to help you avoid the pains of thread management for doing..er..async tasks.

I was thinking of maybe introducing interfaces to provide the data for example a onSuccess listener and onFail Listener. so any suggestions on this?

Not quite sure what you mean here, but certainly, you want to handle failure gracefully. One way to do this is based just on the return value of your AsyncTask, but if you have many different possible failure scenarios, separating them them with a listener/callback pattern is definitely a valid option. I'd personally make not two but one listener, like this:

interface MyHttpCallListener {
  public void onSuccess(MyResult returnVal);
  public void onFailure(MyError error);
}

It seems cleaner to me.

thank you.

No problem.

like image 169
Cheezmeister Avatar answered Sep 18 '22 17:09

Cheezmeister


I like to use the Intent Service API for this kind of thing. The benefit is you are making new asynctasks all over the place and you can que up your requests to the server. The drawback is you can only make one request at a time. But I actually prefer to que them up and execute one at a time so this was good for me.

like image 31
Nathan Schwermann Avatar answered Sep 18 '22 17:09

Nathan Schwermann


I recommend to go with Async Task.

like image 42
Rohit Mandiwal Avatar answered Sep 19 '22 17:09

Rohit Mandiwal