Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use "_activity = this;"?

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?

like image 381
Anonsage Avatar asked Dec 30 '12 03:12

Anonsage


2 Answers

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.

like image 171
Morgan Avatar answered Sep 28 '22 02:09

Morgan


It is not good practice.

Apart from not achieving anything (that can't be done by using this directly):

  • it makes the parent object bigger (by one reference),
  • it is potentially a bit slower, and
  • it makes your code more fragile; e.g. if someone accidentally assigns a different value to the variable.

I would argue that the code is less readable, but you might not agree with that.

like image 25
Stephen C Avatar answered Sep 28 '22 00:09

Stephen C