Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-static method 'getSharedPreferences (java.lang.String, int)' cannot be referenced from a static context

I have an app, and I am trying to limit the number of button clicks to five, and then once the user has pressed this button five times it should disable.

However I am getting the above error and I am not sure why.

Any ideas ?

          buttonadd.setOnClickListener(new OnClickListener () {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
            startActivity(intent);

            int clicks = 0;
            clicks++;

            if (clicks >= 5){
                buttonadd.setEnabled(false);
            }

            SharedPreferences prefs = Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("clicks", clicks);
            editor.apply();

        }

    });
like image 352
MNT Avatar asked Feb 11 '23 12:02

MNT


2 Answers

You are wrongly trying to use the virtual method getSharedPreferences() in a static way, that's why its giving that compile-time error.

If that code is in an Activity, replace

Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

with

getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

If it is in a Fragment, use

getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

EDIT:

use

if (clicks >= 5){
    buttonadd.setEnabled(false);
    buttonadd.setClickable(false);
    buttonadd.setFocusable(false);
    buttonadd.setFocusableInTouchMode(false);
}

and make clicks a class member, i.e. declare it as

private int clicks;

in the Activity.

EDIT 2:

I think I have understood the mistake you are making. In your code, replace

int clicks = 0;

with

SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.getInt("clicks", 0);

Try this. This should do it.

like image 126
Y.S Avatar answered Feb 13 '23 02:02

Y.S


It means that you need an instance of a Context object to call the getSharedPreferences() method. If you're inside an Activity, try this:

this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE)
like image 34
Chris Avatar answered Feb 13 '23 02:02

Chris