[Solved] How to send ‘this’ as variable


Just declare a parameter of the appropriate type (whatever this is in the code mStrawberry.foo(this)):

public class Strawberry{

    public Strawberry(){}

    foo(TheRelevantType thisVariable ){ // ***
         thisVariable.doSomething();    // ***
    }

}

In the above, I’ve used TheRelevantType.

I know this is MainActivity.this bud I have to use different class not only MainActivity…

If you need to have a method that accepts instances of two different classes, you do that by having both classes implement an interface with the common aspects you need to use:

interface ActivityCommon {
    void doSomething();
}

class ThisActivity implements ActivityCommon {
    public void doSomething() {
        System.out.println("This is ThisActivity's doSomething");
    }
}

class ThatActivity implements ActivityCommon {
    public void doSomething() {
        System.out.println("This is ThatActivity's doSomething");
    }
}

class Strawberry {
    foo(ActivityCommon common) {
        common.doSomething();
    }
}

…and/or use a common base class, which looks very similar:

class ActivityBase extends Activity { // Or whatever the base should be
    abstract void doSomething();
}

class ThisActivity extends ActivityBase {
    @Override
    public void doSomething() {
        System.out.println("This is ThisActivity's doSomething");
    }
}

class ThatActivity extends ActivityBase {
    @Override
    public void doSomething() {
        System.out.println("This is ThatActivity's doSomething");
    }
}

class Strawberry {
    foo(ActivityBase activity) {
        activity.doSomething();
    }
}

3

solved How to send ‘this’ as variable