tags:

views:

45

answers:

1

I have to use context in many places of my code such as database operations, preference operations, etc. I don't want to pass in context for every method.

Is it a good practice to create a reference to application context at the main Activity and use it anywhere such as database operations? So, I don't need some many context in method parameters, and the code can avoid position memory leak due to use of Activity Context.

public class MainActivity extends Activity  {

    public static Context s_appContext;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        s_appContext = this.getApplicationContext();
+1  A: 

To me it smells like a hack although I do agree it can be a pain having to pass all those contexts around. At least one problem I see with that approach is when trying to unit test any of your code needing a context - now everything depends on your main activity's onCreate method having been called.

JRL