How Do I Get The Context From Within An Activity Class?
While I'm trying to initialize context using getActivity(), Android Studio shows an error 'could not resolve symbol'. How do I get the context from within an activity class?
Solution 1:
Don't use getActivity
. Use this
.
For example:
Contextcontext=this;
getActivity()
is used if you are inside fragment. In an activity, you can get by using the this
keyword.
By the way, inside an activity, you don't need to use context
, getSharedPreferences()
method is already present in Activity
. Simply call getSharedPreferences()
method without context
reference.
Solution 2:
privatevoidsaveScore() {
Context context = FullscreenActivity.this;
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
}
Post a Comment for "How Do I Get The Context From Within An Activity Class?"