quad
quad

Reputation: 882

Async Task does not start from non activity

Here is my code in the activity in my project:

    CustomClass custom = new CustomClass(); 
    //Passing an array list
    result = custom.getResults(list);

Here CustomClass is a class in the library project and the method getResults(list) starts an AsyncTask.

getResults() method :

    public List<String> getResults(List<String> string){        
        List<String> result= new ArrayList<String>();
        BackgroundTask task =  new BackgroundTask();
        task.execute(string);
        result= task.get();
        return result;
    }

My Async task :

    public class BackgroundTask extends AsyncTask<List<String>, Integer, List<String> >{
    List<String> results= new ArrayList<String>();
    @Override
    protected List<String> doInBackground(List<String>... params) {
        for (int i=0; i<params[0].size();i++) {
            // someOperation
        }
        return results; 
    }
    @Override
    protected void onPostExecute(List<String> result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }


}

Problem : The AsyncTask is not started.When I debug and try to enter into the AsyncTask class I get The source attachment does not contain the source for the file classloader.class. Can someone help me here ? thank you.

Upvotes: 0

Views: 1319

Answers (1)

Dale Wilson
Dale Wilson

Reputation: 9434

The get() method blocks the UI thread which means onPreExecute can't run (it has to run in the UI thread) Thus the background thread will never be started.

Get rid of the call to get() and move the "return the value" logic to onPostExecute.

And NEVER block when you are in the UI thread.

Upvotes: 1

Related Questions