Last Updated: February 25, 2016
·
5.954K
· ldurazo

Sending application context to asynctask

A while ago (yesterday) i ran into a problem that looked rather easy:

Sending the context of my activity to an asynctask, in order to fill a ListView item in the background of my activity; my first code looked like this:

public class AndroidTabActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.listlayout);
     new myAsyncTaskChildclass().execute("handsome String argument")
}

And then tried to set the list adapter of my activity from inside the AsyncTask thread, like this:

protected void onPostExecute(String someJsonFileConsumedtoString){
setListAdapter(new ChildOfBaseAdapter(this, mList);
}

needles to say, sending the context of the AsyncTask class gave nothing but a bunch of errors, i quickly switched the argument to getApplicationContext() to look like this:

protected void onPostExecute(String someJsonFileConsumedtoString){
setListAdapter(new ChildOfBaseAdapter(getApplicationContext(), mList);
}

The layout was showing up content just fine, as my app was a twitter feed i decided to make links clickable by giving my textview an enabled autolink property in the .xml file of the layout (quite easy task: http://stackoverflow.com/questions/18222433/how-to-make-links-in-textview-clickable-in-android)

But my app kept crashing everytime i clicked any URL from the feeder, after some lookout the solution was both easy to implement but hard to notice:

getApplicationContext cannot be used further to listen to the actions of the view, as it gives the control of the application as a whole but can't handle single activities calls; autolink for example

The final solution was to set a constructor on the AsyncTask class, sending the activity as an argument in order to sent that particular activity into the adapter and making it able to open the browser on each of the links that can be clicked.

Solution code as follows:

public DownloadTweetsTask(ListActivity activity) {
       this.activity = activity;
    }

protected String doInBackground(String... searchName) { ... }

protected void onPostExecute(String result){
        activity.setListAdapter(new ChildOfBaseAdapter(activity, mList);
    }

And on the onCreate() of your activity just call the AsyncTask object with the activity as an argument.

public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.listlayout);
       new myAsyncTaskChild(this).execute("handsome String argument")
   }

-