Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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;
        }      

}

Solution 2:

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..


Post a Comment for "How To Avoid Static Context Reference When I Need To Use A Activity Context?"