looking for some solutions? You are welcome.

SOLVED: Switch compact Android SharedPreferences is not working

Mahesh CS:

SharedPreferences in the below code does not work as required. Where am I going wrong? The SharedPreferences is saved on click, and the same is values are being retrieved OnCreate and OnResume in my Android activity.

Code:

mySwitch = (SwitchCompat) findViewById(R.id.atten);
strttime = (TextView) findViewById(R.id.textView5);
endtime = (TextView) findViewById(R.id.textView6);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
silent = settings.getBoolean("switchkey", false);
mySwitch.setChecked(silent);

mySwitch.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        final SwitchCompat btn = (SwitchCompat) v;
        final boolean switchChecked = silent;

        String message = "Are you sure you want to Logout?";
        if (!btn.isChecked()) {
            message = "Are you sure you want to Login?";
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyAlertDialogStyle); // Change "this" to `getActivity()` if you're using this on a fragment
        builder.setMessage(message).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
            public void onClick(DialogInterface dialog, int i) {
                // "Yes" button was clicked
                if (switchChecked) {

                    Log.d("You are :", "Checked");

                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putBoolean("switchkey", true);
                    editor.apply();
                } else {
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putBoolean("switchkey", false);
                    editor.apply();
                }
            }
        }).setNegativeButton("Cancel", null).show();
    }
});



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent