Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the context in a class that implements Runnable

I have an app in android that in a different thread from the UI(which implements Runnable)

I receive some data(GPS data in the form of latitude and longitude) and from this data I

wanna find out the right address by passing it to a Geocoder.....after that the address returned by Geocoder I store it in a database:

Here is how I do these things:

public class Client implemets Runnable{


public void run()
{

Geocoder myLocation=new Geocoder(getApllicationContext,Locale.getDefault());



}

}

but I get error here:

Geocoder myLocation=new Geocoder(getApplicationContext,Locale.getDefault());

Runnable doesn't know who getApplicationContext is.....I tried with "this" instead but the same story.....

Now which is the right context to pass in to the Geocoder constructor????

Here is how the Geocoder constructor looks like:

Geocoder myLocation =new Geocoder(context,locale);

In my activity I do this:

public class Server2 extends Activity {


public void onCreate(Bundle icicle) {


ClientThread_special client = new ClientThread_special(db);//here is where I start thread


        new Thread(client).start();
}


}

public class ClientThread_special implements Runnable {



 public ClientThread_special(DBAdapter db){

     this.db=db;
    }


 public void run() 

{

Geocoder myLocation=new Geocoder(getApllicationContext,Locale.getDefault());


}


}

How should I modify the constructor

public ClientThread_special(DBAdapter db){

     this.db=db;

    }

in order to have in my Runnable the context of Server2?

like image 477
embry Avatar asked May 29 '11 11:05

embry


2 Answers

I guess your class ClientThreadSpecial is a separate class (not an inner class)? If so, why don't you pass the context from your calling Activity?

If it is an inner-class, it's even easier. Assuming your ClientThreadSpecial-class is an inner class of the MyActivity-class (which extends Activity), you can use something like this:

Geocoder myLocation=new Geocoder(MyActivity.this,Locale.getDefault());
like image 171
Lukas Knuth Avatar answered Nov 14 '22 23:11

Lukas Knuth


You can't use this because this refers to a Runnable. Since the Runnable is defined within MyActivity (replace with your Activity / Service name), you can refer to MyActivity.this.

like image 37
mah Avatar answered Nov 15 '22 00:11

mah