Should I use "_activity = this;
"?
I've seen _activity referenced many times in sample code. So, I arbitrarily decided that it looked like a good practice and have been using in all my code for awhile (over a year). But, before I start spreading the word around more I wanted to find some proper documentation that using a global (activity-local) context variable is good practice or not.
Anybody have ideas/thoughts/links? Know of any pros and cons?
One resource that I have found so far seems to say there are good and bad times to use this
I know that I could use this
or MainActivity.this
, but that's not the question.
..Just in case you don't know what I'm talking about, here is a trvial example made up on the spot:
public class MainActivity extends Activity {
MainActivity _activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activity = this; // TODO: Find out if this is good practice?
setContentView(R.layout.activity_main);
}
public void onClickButton(View v) {
Toast.makeText(_activity, "Five boxing wizards", Toast.LENGTH_LONG).show();
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(_activity, "asdf", Toast.LENGTH_LONG).show();
}
});
}
}
EDIT: Another side-question for the comments: By a show of hands, who actually uses _activity
?
This is not good practice. Simply use this
in most cases, and MainActivity.this
when creating an anonymous subclass, etc.
I think the right question to ask yourself is, "does adding this member variable do anything for me", or "is there anything I can do with _activity
that I can't do with this
. I can tell you the answer is "no", but you should decide for yourself whether it is true.
It is not good practice.
Apart from not achieving anything (that can't be done by using this
directly):
I would argue that the code is less readable, but you might not agree with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With