0

I have to use the context variable a lot in Android, and I end up having to pass it around a lot which gets tedious. Is it okay to have a global context variable in my main activity assigned in its onCreate method and just use that context variable with a getter method whenever I need context? For example:

public class MainActivity extends AppCompatActivity {

  private Context context = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      // ... code

      Context = this;
  }

  // Context getter method
  public Context getContext(){

    return context;
  }
}

(a) Can I use this context variable from my main activity when I need to called a method from another activity which require context?

(b) What about when I call a method from a fragment which requires context?

the_prole
  • 8,275
  • 16
  • 78
  • 163
  • use application. see this answer http://stackoverflow.com/a/38931824/1025379 – Hun Jan 18 '17 at 01:15
  • The only problem I see with this approach is you can't access the individual activity methods by casting `context` to activity. If that works go with this. – Nitesh Verma Jan 18 '17 at 02:28

2 Answers2

0

I suggest you define the context variable in MyApplication,which extented Application: public class MyApplication extends Application { public static Context mContext;//instantiation it in onCreate(); ... } In your AndroidManifest.xml,<Application android:name=".MyApplication" .... now you can use mContext in your Code everywhere.

志威梦
  • 136
  • 3
0

To my experience and knowledge, Using the application context is a horrible and naive approach. Read https://stackoverflow.com/a/7298955/3758972 for more information.

What you can do instead is make every Activity extend a common BaseActivity class and define and initialise your context in BaseActivity onCreate method like below :

public class BaseActivity extends AppCompatActivity {

private Context context = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  Context = this;
}

// Context getter method
public Context getContext(){
return context;
}
}

Can I use this context variable from my main activity when I need to called a method from another activity which require context?

yes, now you can extend all your activities and cast the context to specific Activity to access methods.

((ActivityA)getContext()).methodOfAActivity();

((ActivityB)getContext()).methodOfBActivity();

What about when I call a method from a fragment which requires context?

Similar to above you can use and cast context to get access to activity methods in fragment.

I hope it'll guide you.

Community
  • 1
  • 1
Nitesh Verma
  • 2,460
  • 4
  • 20
  • 36