jay tandel
jay tandel

Reputation: 177

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?

Upvotes: 4

Views: 42059

Answers (2)

Sasi Kumar
Sasi Kumar

Reputation: 13368

private void saveScore() {
    Context context = FullscreenActivity.this;
    SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key),  Context.MODE_PRIVATE);
}

Upvotes: 1

Pawneshwer Gupta
Pawneshwer Gupta

Reputation: 2342

Don't use getActivity. Use this.

For example:

Context context = 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.

Upvotes: 29

Related Questions