Cilenco
Cilenco

Reputation: 7117

Start AsyncTask in Method and return its value

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?

Upvotes: 0

Views: 1368

Answers (2)

saravana
saravana

Reputation: 564

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);
}

Upvotes: 1

Victor Ronin
Victor Ronin

Reputation: 23268

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"?

Upvotes: 1

Related Questions