Studio2bDesigns
Studio2bDesigns

Reputation: 648

Android - SharedPreferences - Adjusting Code based on Preference Value?

Implementing the User's chosen Preferences into my Code is a new conquest for me.
I've successfully implemented a portion of the Preferences to Code, but could use advice.

I have chosen to use the Preferences-API and a PreferenceFragment for my App Settings.
So far I have my SettingsActivity set up, working, and updating new values correctly.
However, some assistance is needed now that I'm implementing Preference values to Code.

There are 2 Preferences which I am struggling to implement into Code.
However, for now, I'll discuss just 1 of them.. The details are as follows :

Preference = Notification Type
( key = pref_notificationType ) - ( constant String = PREF_NOTIFICATION_TYPE )

Values :
Sound and Vibration
Sound only
Vibration only
Silent

( NOTE : These are the exact value names for this Preference ).


I want to do something along these lines, except correctly, and efficiently:

public void notificationType() {

    SharedPreferences getPrefs = PreferenceManager
        .getDefaultSharedPreferences(getApplicationContext());

    final String notifType = 
        getPrefs.getString(PREF_NOTIFICATION_TYPE, "Sound and Vibration");

    switch (notifType) {

        case ("Sound and Vibration"):
            //  Create Notification with SOUND (AND) VIBRATION
            break;

        case ("Sound only"):
            //  Create Notification with SOUND (only)
            break;

        case ("Vibrate only"):
            //  Create Notification with VIBRATION (only)
            break;

        case ("Silent"):
            //  Create Notification SILENTLY
            break;

        default:
            //  The default is "Sound and Vibration"
            break;
    }
}


If anybody could please provide some advice on how to go about this, I would greatly appreciate it!

Thanks in advance!

Upvotes: 1

Views: 54

Answers (1)

Thiago Neves
Thiago Neves

Reputation: 91

I think in this case the best way create Enum and compare this in swithc.

enum NotificationType {
  SOUND_AND_VIBRATE, SOUND_ONLY, VIBRATE_ONLY, SILENT 
}
//and

switch (NotificationType) {
      case SOUND_AND_VIBRATE:
      case SOUND_ONLY:
      case VIBRATE_ONLY:
      case SILENT:
}

Upvotes: 1

Related Questions