Skip to content Skip to sidebar Skip to footer

How Can I Pass An Object To A New Thread Generated Anonymously In A Button Listener

I would like to pass an object (docket for printing) to a new thread which will print the docket. My code is: private final Button.OnClickListener cmdPrintOnClickListener = new

Solution 1:

You could create your own Runnable class implementation:

privateclassRunnableInstanceimplementsRunnable {

    protectedDocket docket;

    publicvoidrun() {
        //do your stuff with the docket
    }

    publicvoidsetDocket(Docket docket) {
        this.docket = docket;
    }

}

And then use it to create the thread

publicvoidonClick(View v) {
        RunnableInstancetarget=newRunnableInstance();
        target.setDocket(docketInstance);
        newThread(target).start();
    }

If you need to stick to an anonymous class you could do:

publicvoidonClick(View v) {
        finalDocketdocket= docketInstance;
        Runnabletarget=newRunnable(){
            publicvoidrun() {
                // do your stuff with the docket
                System.out.println(docket);
            }
        };
        newThread(target).start();

    }

But you have make sure you assign the instance to a final variable.

Post a Comment for "How Can I Pass An Object To A New Thread Generated Anonymously In A Button Listener"