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();
        }
    });
                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.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With