jay tandel jay tandel - 1 month ago 6x
Android Question

How to get context within activity class

While I'm trying to initialize context using getActivity() android studio shows error of could not resolve symbol.

class FullscreenActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {

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


Don't use getActivity.

use this.

For example

Context context = this;

(getActivity() is used if you are inside fragment. in Activity you can get by using this keyword.)

And by the way inside Activity you don't need to use context, getSharedPreferences() method is already present in Actiity. simply call getSharedPreferences() method without context reference.