Alejandro Huerta
Alejandro Huerta

Reputation: 1144

How can I pass a reference to the current activity

I am trying to pass a reference of the current activity to an object but can't seem to find a method that will do this easily. Previously I was able to do this simple passing with the "this" reference of the current context. I then changed my activity from implementing OnClickListener to creating an OnClickListener object so that I could pass it as a parameter. This is when I ran into trouble as I was trying to create the object after I clicked on a button, this means I can no longer pass the activity with "this" because "this" is now a reference of the OnClickListener.

public class MyActivity extends Activity {
    private Object mObject;

    private OnClickListener mListener = new OnClickListener() {
        public void onClick(View v) {
            Object mObject = new Object(this);
        }
    }
}

public class Object {
    private Activity mActivity;
    public Object(Activity a) {
        mActivity = a;
        mActivity.setContentView(R.layout.layout);
    }
}

Seems like an easy fix but I can't find the answer...

Any help is greatly appreciated.

Upvotes: 2

Views: 4620

Answers (2)

rogerkk
rogerkk

Reputation: 5695

You are right, this now references the OnClickListener, as it references the current class, and you are working inside an anonymous class. You can reference the outer activity by passing mActivity.this:

Object mObject = new Object(mActivity.this);

Btw: I think I'd rename the mActivity class, as normal class naming convention is for it to start with an uppercase letter.

Upvotes: 6

ernazm
ernazm

Reputation: 9258

Add mActivity. to this

Object mObject = new Object(mActivity.this);

In your context, this refers to a listener instance, but you need the outer class's instance there, so you need to add class name to this

Upvotes: 3

Related Questions