Leandro Silva
Leandro Silva

Reputation: 814

How to avoid static context reference when I need to use a activity context?

After read this topic avoiding memory leaks some doubts arouse.

If I need to use an activity context (example: inflate a view in a PopupWindow class to show a popup) how can I hold the context of actual activity to do it? If I need to avoid a static context reference the only way to do it is creating an attribute in my class? And all the other classes I'll need the actual activity context I need to do it?

update-

I want to use this actual activity context in many classes that don't inherited Context, like I use with the application Context in my Application class that has a static method called getApplicationContext() declared. This method follows the Singleton Design Pattern and works fine.

Upvotes: 1

Views: 2126

Answers (2)

Eric Levine
Eric Levine

Reputation: 13564

Working from the code you linked in the comments, why not do this:

//my main activity
public class ExampleStaticReferenceActivity extends Activity {
        //...

    public void methodCalledWhenUserPressesButton(){
        LinearLayout masterLayout = (LinearLayout) findViewById(R.id.masterLayout);
        //now passing a reference to the current activity - elevine
        masterLayout.addView(ButtonCreator.createButton(this));
    }
}

//this class is in another package
public class ButtonCreator {
        //added a Context parameter - elevine
        public static Button createButton(Context context) {
                Button button;

                button = new Button(context);
                //... some configurations for button
                return button;
        }      

}

Upvotes: 2

ngesh
ngesh

Reputation: 13501

That will crash your Application since Your Activity will be killed by OS when it runs out of Resources thus Context will also be null.. And its meaningless to give A background Activities Instance when you want to show pop up in the Foreground Activity.. What the Blog says is avoid passing activity.this where even getApplicationContext() can do the job..

Upvotes: 0

Related Questions