Reputation: 2057
I wrote simple one line to get context of application in android.
There is nothing else except new project with one activity.
I wrote this code in onCreate Method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getContext();
}
It asks me to replace getContext with getBaseContext.
Why I can't use only getContext as it is present?
Upvotes: 0
Views: 3127
Reputation: 3177
Please make your understanding clear on android context-
getContext() or View.getContext(): Returns the context the view is running in, through which it can access the current theme, resources, etc.
getApplicationContext() or Activity.getApplicationContext(): Application context is associated with the Applicaition and will always be the same throughout the life cycle.
Context.getBaseContext():should not be used just use Context instead of it which is associated with the activity and could possible be destroyed when the activity is destroyed.
And please have a look on this blog-post to avoid android context related memory leak problem.
(You may come across so many but you need to choose that fit your need)
Upvotes: 1
Reputation: 21
Context provides information about the Actvity or Application to newly created components. And be more specific on getting your intended Context, whether for your View/whole Activity/you are trying to get ContextWrapper.
Try this more info getContext API
Upvotes: 0
Reputation: 8134
getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).
Get context in Android?
Difference in context this and getContext()
http://android.okhelp.cz/get-context-java-android-example/
Upvotes: 0
Reputation: 5068
In general there are two type of classes. Ones that extend ContextWrapper class (Activity, Service, Application) and those that do not extend it (like View).
If class extends ContextWrapper then you can use this as Context. Such classes normally do not have getContext() method. Those classes that do not extend ContextWrapper but still save and use Context normally expose getContext() function. And you cannot use this as Context in such cases.
And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper and have getContext at the same time.
coutesy : @inazaruk
getContext() is not defined for a class that extends an Activity
Upvotes: 0
Reputation: 133560
Just use getApplicationContext()
http://developer.android.com/reference/android/content/Context.html
Upvotes: 0