Genadinik
Genadinik

Reputation: 18639

How to get the class reference inside an onClick listener in Android?

I am trying to call this method inside an onClick listener:

        mHelper.launchPurchaseFlow(this,
                SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                RC_REQUEST, mPurchaseFinishedListener, payload);

But because it is inside an onClick listener, the reference to this becomes not the reference to the class, but the onClick listener. Is there a way to pass the class reference if this code is inside the onClick listener?

Thanks!

Upvotes: 2

Views: 2277

Answers (3)

Apoorv
Apoorv

Reputation: 13520

There can be 2 cases

1) If your class extends Context eg. Activity,Service you can do

mHelper.launchPurchaseFlow(getApplicationContext(),SKU_INFINITE_GAS,IabHelper.ITEM_TYPE_SUBS,RC_REQUEST,mPurchaseFinishedListener, payload);

2) If your class does not extend Context then you need to pass an object of Context to that class in some way and call

mHelper.launchPurchaseFlow(mContext.getApplicationContext(),SKU_INFINITE_GAS,IabHelper.ITEM_TYPE_SUBS,RC_REQUEST,mPurchaseFinishedListener, payload);

where mContext is an object of Context class

Upvotes: 1

Giru Bhai
Giru Bhai

Reputation: 14408

Define Context mContext=null; in your activity and in oncreate method of activity make instance of this as

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         mContext = this;
}

and use

mHelper.launchPurchaseFlow(mContext,
                    SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                    RC_REQUEST, mPurchaseFinishedListener, payload);

or directly use

mHelper.launchPurchaseFlow(youractivity.this,
                        SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                        RC_REQUEST, mPurchaseFinishedListener, payload);

Upvotes: 2

tonys
tonys

Reputation: 3984

If your containing class is called e.g.MyClass then you can just use MyClass.this:

 mHelper.launchPurchaseFlow(MyClass.this,
                SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS,
                RC_REQUEST, mPurchaseFinishedListener, payload);

Upvotes: 6

Related Questions