jeudi 1 septembre 2016

How to save checkBox state using SharedPreferences in android

I have an AlertDialog CheckBox. I want to save checkbox state in sharedPreferences when I check, and again when app restart and I open the Dialog checkbox, state auto check which I save. How to make this please help me.

Here is my code:

    set_repeat_days = (LinearLayout)findViewById(R.id.repeat_days);
    set_repeat_days.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);

            String[] days = new String[]{"Monday", "Thursday", "Wednesday", "Tuesday", "Friday", "Saturday", "Sunday"};
            final boolean[] checkedDays = new boolean[]{false, true, true, true, true, true, true};
            final List<String> daysList = Arrays.asList(days);

            builder.setMultiChoiceItems(days, checkedDays, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
                    // Update the current focused item's checked status
                    checkedDays[which] = isChecked;
                    // Get the current focused item
                    String currentItem = daysList.get(which);

                    Toast.makeText(getApplicationContext(),
                            currentItem + " " + isChecked, Toast.LENGTH_SHORT).show();
                }
            });
            // Specify the dialog is not cancelable
            builder.setCancelable(false);
            builder.setTitle("Repeat");

            // Set the positive/yes button click listener
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    repeat_list = (TextView)findViewById(R.id.repeat_list);
                    for (int i = 0; i<checkedDays.length; i++){
                        boolean checked = checkedDays[i];
                        if (checked){
                            String day = (daysList.get(i) + ", ");
                            repeat_list.setText(day);
                        }
                    }

                }
            });
            // Set the neutral/cancel button click listener
            builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });




Aucun commentaire:

Enregistrer un commentaire