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?