mardi 3 janvier 2017

Saving state of checkbox and alarm

I'm new to android and I need to make an app that starts an alarm when a check box is checked and keeps the state of the check box saved. I tried to use an int to save values of checkbox and start alarm but it doesn't work.

public int getValueC(String key) {
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    int value = sharedPref.getInt(key, 0);
    return value;
}
public void saveValueC(String key, int value) {
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt(key, value);
    editor.apply();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_a_d_q);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final CheckBox checkBox1 = (CheckBox) findViewById(R.id.mc);
    final String keyC = "somekeyC";
    c = getValueC(keyC); 

    checkBox1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            c++;
            saveValueC(keyC,c);

            if (c%2==0){
                Toast ToastMessage = Toast.makeText(getApplicationContext(), "off", Toast.LENGTH_LONG);
                //View toastView = ToastMessage.getView();
                //toastView.setBackgroundColor(Color.YELLOW);
                ToastMessage.show();
                alarmManagers.cancel(pendingIntent);
            }
            else{
                Toast ToastMessage = Toast.makeText(getApplicationContext(), "on", Toast.LENGTH_LONG);
                //View toastView = ToastMessage.getView();
                //toastView.setBackgroundColor(Color.YELLOW);
                ToastMessage.show();
                alarmManagers.setRepeating(AlarmManager.RTC,  calendar.getTimeInMillis(),2*60*1000,pendingIntents);

                checkBox1.isChecked();
            }});
   if (c%2==0){

        Toast ToastMessage = Toast.makeText(getApplicationContext(), "Even number", Toast.LENGTH_LONG);
        //View toastView = ToastMessage.getView();
        //toastView.setBackgroundColor(Color.YELLOW);
        ToastMessage.show();

    }
    else{

        checkBox1.isChecked();
    }

I did not include the alarm manager and intent code because the alarm works fine. I just need to save value to check box and when it's checked; it should turn on the alarm and save the state of check box. When it's unchecked ; it should turn off the alarm and save the start of check box.

I've spent hours trying to figure it out. If you know the issue, plz let me know. Thank you




Aucun commentaire:

Enregistrer un commentaire