I hope the question is I want to create a method which starts an AsyncTask, waits until the Task ends and then return the value which is provided in the onPostExecute method. So from my main I only want to call the method and get the value which is returned by te AsyncTask. Is that possible? And how does this method have to look like?
Asked
Active
Viewed 1,365 times
0
-
Post what you have so far. Also, [see this answer](http://stackoverflow.com/questions/18517400/inner-class-can-access-but-not-update-values-asynctask/18517648#18517648) it should help – codeMagic Sep 14 '13 at 17:25
2 Answers
1
Let say you have an instance of AsyncTask called task. In such case you do:
task.execute(parameters);
Result result = task.get();
Method get()
will wait until task is completed and will return result from it.
P.S. You are trying to execute asynchronous task synchronously, which raises a question - "Do you need AsyncTask at all"?

Victor Ronin
- 22,758
- 18
- 92
- 184
-
-1 for suggesting `get()` +1 for describing the effects of it like freezing the `UI` until its done. There are a lot of reasons for needing to do what the OP is trying to do and ways to do it efficiently like using an `interface` – codeMagic Sep 14 '13 at 17:55
-
Still need when download Image from the Internet inside a callback method which return this image. – nhoxbypass Sep 12 '17 at 15:54
1
Just execute AsyncTask and do call the particular method which contains logic onPostExecute() method. See the example code what i have used.
protected void onCreate(Bundle savedInstanceState) {
customContactList = (ListView)findViewById(R.id.listView1);
ContactsAsyncTask newTask = new ContactsAsyncTask(this);
newTask.execute();
}
private class ContactsAsyncTask extends AsyncTask<Void, Void, ArrayList<String> >{
ProgressDialog dialog;
private SecondActivity context;
public ContactsAsyncTask(SecondActivity secondActivity) {
// TODO Auto-generated constructor stub
this.context = secondActivity;
}
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
context.useContacts(result);
}
public void useContacts(ArrayList<String> data) {
adapter = new CustomAdapter(SecondActivity.this,data);
customContactList.setAdapter(adapter);
}

saravana
- 544
- 1
- 7
- 26