javaandroiduiswitchischecked

isChecked() returns true though the switch is not checked


I have used a switch to set the notifications. I want to save the notifications if the switch is checked i.e. notification is on.

But if I on the switch and again off the switch and save the event. Then also the notification is getting set.

As I did debug on if(isChecked() == true) , it returns true if I on and off the switch once. If I do not change the state of switch it returns false.

What's wrong?

 notify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            if (isChecked) {

                linearSelectTime.setEnabled(true);
                linearSelectTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(AddEventActivity.this);

                        int selected = 0;

                        builder.setSingleChoiceItems(R.array.time_array, selected,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int item) {

                                        String[] time = getBaseContext().getResources().getStringArray(R.array.time_array);

                                        notifyTime.setText(time[item]);

                                        notificationTime = time[item];

                                        dialog.dismiss();
                                    }
                                });
                        builder.show();
                    }

                });
            } else {

                alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                intent = new Intent(getApplicationContext(), NotificationReceiver.class);
                pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), RQS_1, intent, 0);
                alarmManager.cancel(pendingIntent);

                notificationTime = "";
                notifyText.setVisibility(View.INVISIBLE);
                linearSelectTime.setEnabled(false);
            }

        }
    });

on save:

                        if (notify.isChecked()) {
                            setNotificationTime(c);

                        }

What's going wrong here.?


Solution

  • OnCheckedChangeListener doesn't work properly most of the time. First set OnClickListener on your checkbox and in that method use isChecked to getValue of your checkbox like this

        checkBox.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        if (checkBox.isChecked())
        {
    
        }else {
    
        }
       }
      });