Switch gets on loop with setChecked
<p>I have a switch that sends a SMS. </p>

<ul>
<li>if disabled, sends an enable SMS</li>
<li>if enabled, sends a disable SMS</li>
</ul>

<p>Before sending this SMS, an alertDialog appears to request the user to confirm that wants to make the change. </p>

<p>If the user selects "OK", then the message is send and the alertDialog dissmissed. </p>

<p>If the user selects "No", the alertDialog is dissmissed. But the switch has changed it's state previously, so it should return to the previous state. The only way that I know to do this is to use <code>switch.setChecked(boolean)</code>, the problem is that if I use this, the switch gets into a loop and shows me all the time the alertDialog with the enabling or dissabling option.</p>

<p>This is the code:</p>

<pre><code>    switch_1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (isChecked) {
                new_state = 1;
            }else {
                new_state = 0;
            }
            AlertDialog.Builder builder =
                    new AlertDialog.Builder(getActivity());
            builder.setNegativeButton(R.string.btncancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (new_state == 1) {
                        new_state = 0;
                        switch_1.setChecked(false);
                    }else {
                        new_state = 1;
                        switch_1.setChecked(true);
                    }
                }
            });
            builder.setPositiveButton(R.string.btnaccept, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    ((MainActivity)getActivity()).sendCommand(new_state);
                }
            });
            builder.show();
        }
    });
</code></pre>

<p>This code is inside a fragment. So basically I would like to know how to return the switch to it's previous state if the user hits the negative button, without getting into this loop.</p>