views:

407

answers:

3

So I'm working out my first multi-threaded application using Android with the AsyncTask class. I'm trying to use it to fire off a Geocoder in a second thread, then update the UI with onPostExecute, but I keep running into an issue with the proper Context.

I kind of hobbled my way through using Contexts on the main thread, but I'm not exactly sure what the Context is or how to use it on background threads, and I haven't found any good examples on it. Any help? Here is an excerpt of what I'm trying to do:

public class GeoCode extends AsyncTask<GeoThread, Void, GeoThread> {
  @Override
  protected GeoThread doInBackground(GeoThread... i) {
    List<Address> addresses = null;
    Geocoder geoCode = null; 
    geoCode = new Geocoder(null); //Expects at minimum Geocoder(Context context);
    addresses = geoCode.getFromLocation(GoldenHour.lat, GoldenHour.lng, 1);
  }
}

It keeps failing at the sixth line there, because of the improper Context.

+1  A: 

I did some more research, and someone suggested passing it to the thread (not sure why I didn't think of that). I passed it to the Geocoder thread through an argument, and just like that, it worked.

Michael
+2  A: 

The Context is an object which provides accees to application runtime environment. In most cases when you need to obtain objects from Android environment, such as resources, views, infrastructure classes etc -- you need to have Context in your hands.

To obtain Context instance is very simple when you're in the Activity class -- Activity itself is a subclass of the Context, so all you need to do -- is to use 'this' keyword to point on your current context.

Whever you create code which might require Context - you should take care to pass Context object from your parent Activity. In case of your example you could add explicit constructor which accepts Context as input argument.

Vlad
A: 

The problem with updating the UI from an AsyncTask is that you need the current activity context. But the context is destroyed and recreated for every orientation change.

Here's a good answer to your question: http://stackoverflow.com/questions/2124701/android-asynctask-context-problem

espinchi