I'm trying to return value from my asynctask in DoInBackground, but calling get() method freezes my UI. How can I re-write my code to a callback method? :
public class GetUrlDataTask extends AsyncTask<String, Integer, String> {
String response;
HttpUtils util;
@Override
protected String doInBackground(String... params) {
try {
util = new HttpUtils(params[0]);
response = util.getContent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
In my activity I get result as response = new GetUrlDataTask().execute("site").get;
I'm not a big fan of having AsycTask tasks in separate classes, especially if you need to use the response. It makes interacting with the response and local variables overly difficult considering how easy it is when implemented as an inner class.
I'm guessing you put it in its own class so you can reuse it. I would consider keeping the AsycTask as an inner class and calling outside reusable objects/methods in doInBackground(). This will keep the code DRY and allow your activity to do what it needs with the response.
You could do something like this:
[UPDATE] Now i suggest to use annotations. With annotations you can inject views, make function as asyncronous process on the compilation step with just a few letters. Check out butterknife library on github.
ButterKnife
You can create interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute
For example:
Your interface:
Your Activity:
And your AsyncTask:
You shouldn't use .get() if the Async task is going to take any decent amount of time (which it usually is).
Instead, you can either use a message/handler/service/etc, or you can simply use the onPostExecute(Result) method.
EDIT: New Code. Based on your description, it seems like you need to use an interface.
If you need to have Asynctask in another class, then an interface is probably your best option.
TestTask.java (your separate Asynctask):
MainActivity.java (or any other activity):