dythe
dythe

Reputation: 841

Issue with boolean on shared preferences

I am currently trying to start a service based on the boolean false or true when the phone boots up. The issue is if i use getBoolean

 boolean isPhysicalSirenFlagged = sp.getBoolean("isPhysicalSirenFlagged", true);
 boolean isSMSSirenFlagged = sp.getBoolean("isSMSSirenFlagged", true);

Both of them will get set to true whenever the phone boots up causing my both my isPhysicalSirenFlagged & isSMSSirenFlagged to be true when. Is it possible to check what is the current boolean of a value?

Code:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     String value = sp.getString("serial", "");
     boolean isPhysicalSirenFlagged = sp.getBoolean("isPhysicalSirenFlagged", true);
     boolean isSMSSirenFlagged = sp.getBoolean("isSMSSirenFlagged", true);

     if (isPhysicalSirenFlagged) {
         //true
         Intent physicaldialog = new Intent(context, PhysicalTheftDialog.class);
         physicaldialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(physicaldialog);
         context.startService(new Intent(context, PhysicalTheftService.class));
     }
     else {
         //false
     }

     if (isSMSSirenFlagged) {
         //true
         Intent smsdialog = new Intent(context, SMSNotificationPasswordDialog.class);
         smsdialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(smsdialog);
         context.startService(new Intent(context, RemoteSirenService.class));
     }
     else {
         //false
     }

Upvotes: 1

Views: 427

Answers (1)

ahodder
ahodder

Reputation: 11439

Have it set to false instead, obviously what ever you are doing is not commiting a change to the SharedPrefereces to indicate the flag. By using false as a default, you will prevent the accidental true assignment to the flags. Truthfully, you should be using int flags (or preferred an enum) to represent this. It is a much safer way of determining the state the device is in. for example:

int NO_STATE    = 0
int IS_THEFTED  = 1
int IS_WAILING  = 2

or

enum State {
    NONE, THEFTED, WAILING;
}

Upvotes: 1

Related Questions