Search code examples
javaandroidmultithreadingrunnable

Android - Refer to main runnable from DialogInterface.OnClickListener


I'm implementing Runnable in my Activity class and have a thread that uses that runnable to get something from SQLite and put it into the activity.

The problem is I want to refer to that Runnable's run() method from the context of a DialogInterface.OnClickListener()...If I try to do like this Thread t = new Thread(getApplicationContext()); I get an error saying The constructor Thread(Context) is undefined but in my onCreate I can do Thread t = new Thread(this);

So how can I reference the Runnable from the DialogInterface.OnClickListener() context...Here is my code adapted for short:

public class MainActivity extends ListActivity implements OnItemClickListener,Runnable {
Thread t = null;
onCreate()...
run()...
OnItemClick(...) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
.
.
.
alert.setItems(options, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            Thread t = new Thread(getApplicationContext()); //this thing doesn't work because it gets the app context as context not as referencing a Runnable's run()
            //Here I want to reference the run() method above
            }
}
}

Solution

  • It seems you can do MainActivity.this.run()

    Or if you want a Runnable, not run(), define this Runnable as a field in your MainActivity

    private Runnable myRunnable = new Runnable() { public void run() {...} }
    

    Or make your MainActivity implements Runnable then you can refer to this runnable as MainActivity.this