Get current activity in base activity intent
Every Activity
or Service
have its own context, so only using this
keyword is enough for you to retrieve the context you want to use.
If your class extends any kind of Activity
, just use this
or YourClassName.this
, or even getContext()
, getApplicationContext()
or getBaseContext()
, everything depends on where you are but in your case, this
or YouClass.this
is enough.
In your first example, MainActivity.this
represents a Context
object. See this for some discussion of what context
is.
Related videos on Youtube
Deep
Updated on June 26, 2022Comments
-
Deep almost 2 years
I have a BaseActivity class which I extend in other activities. I have a menu at at the bottom which consists of 5 buttons. Currently I am using setOnClickListener whenever the menu button is clicked and I have duplicated the code in every activity. Obviously this is not a good practise. If I have to make any small change I have to edit in every activity which becomes cumbersome. So I am trying to optimise it by placing different methods in BaseActivity and calling that method in xml onClick.
The following code says that I am currently on MainActivity.this and it will open FindActivity.class. The following works if the code is in MainActivity class
Public Class MainActivity extends BaseActivity{ Intent intent = new Intent(MainActivity.this, FindActivity.class); startActivity(intent); }
But what I am trying to achieve is having the above code in BaseActivity which will be extended by MainActivity obviously.
Public Class BaseActivity extends ActionBarActivity{ Intent intent = new Intent("This should be MainActivity.class", FindActivity.class); startActivity(intent); }
Now the problem here is I am unsure of how to get the MainActivity.this in the Intent parameter in BaseActivity when I am on MainActivity. Basically I am not sure how to get the context there.
Any help will be greatly appreciated.
Please let me know if the above is unclear and requires more explanation.
Thanks in advance.