android.content.SharedPreferences

Here are the examples of the java api class android.content.SharedPreferences taken from open source projects.

1. PrefStore#getStartup()

Project: linuxdeploy
Source File: PrefStore.java
View license
/**
     * Get list of startup
     * 
     * @param c context
     * @return list of startup separated by a space, e.g. ssh, vnc etc.
     */
public static String getStartup(Context c) {
    SharedPreferences pref = c.getSharedPreferences(getCurrentProfile(c), Context.MODE_PRIVATE);
    String startup = "";
    if (pref.getBoolean("sshstartup", c.getString(R.string.sshstartup).equals("true"))) {
        startup += " ssh";
    }
    if (pref.getBoolean("guistartup", c.getString(R.string.guistartup).equals("true"))) {
        startup += " " + pref.getString("guitype", c.getString(R.string.guitype));
    }
    if (pref.getBoolean("customstartup", c.getString(R.string.customstartup).equals("true"))) {
        startup += " custom";
    }
    return startup.trim();
}

2. SyncthingService#onCreate()

View license
/**
     * Starts the native binary.
     */
@Override
public void onCreate() {
    PRNGFixes.apply();
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    if (isFirstStart()) {
        char[] chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < 20; i++) sb.append(chars[random.nextInt(chars.length)]);
        String user = Build.MODEL.replaceAll("[^a-zA-Z0-9 ]", "");
        Log.i(TAG, "Generated GUI username and password (username is " + user + ")");
        sp.edit().putString("gui_user", user).putString("gui_password", sb.toString()).apply();
    }
    mDeviceStateHolder = new DeviceStateHolder(SyncthingService.this);
    registerReceiver(mDeviceStateHolder, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    new StartupTask(sp.getString("gui_user", ""), sp.getString("gui_password", "")).execute();
    sp.registerOnSharedPreferenceChangeListener(this);
}

3. Prefs#remove()

Project: EasyPreferences
Source File: Prefs.java
View license
/**
     * Removes a preference value.
     *
     * @param key The name of the preference to remove.
     * @see android.content.SharedPreferences.Editor#remove(String)
     */
public static void remove(final String key) {
    SharedPreferences prefs = getPreferences();
    final Editor editor = prefs.edit();
    if (prefs.contains(key + LENGTH)) {
        // Workaround for pre-HC's lack of StringSets
        int stringSetLength = prefs.getInt(key + LENGTH, -1);
        if (stringSetLength >= 0) {
            editor.remove(key + LENGTH);
            for (int i = 0; i < stringSetLength; i++) {
                editor.remove(key + "[" + i + "]");
            }
        }
    }
    editor.remove(key);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        editor.commit();
    } else {
        editor.apply();
    }
}

4. Prefs#getOrderedStringSet()

Project: EasyPreferences
Source File: Prefs.java
View license
/**
     * Retrieves a Set of Strings as stored by {@link #putOrderedStringSet(String, Set)},
     * preserving the original order. Note that this implementation is heavier than the native
     * {@link #getStringSet(String, Set)} method (which does not guarantee to preserve order).
     *
     * @param key      The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference value if it exists, or defValues otherwise.
     * @throws ClassCastException if there is a preference with this name that is not a Set of
     *                            Strings.
     * @see #getStringSet(String, Set)
     */
public static Set<String> getOrderedStringSet(String key, final Set<String> defValue) {
    SharedPreferences prefs = getPreferences();
    if (prefs.contains(key + LENGTH)) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        int stringSetLength = prefs.getInt(key + LENGTH, -1);
        if (stringSetLength >= 0) {
            for (int i = 0; i < stringSetLength; i++) {
                set.add(prefs.getString(key + "[" + i + "]", null));
            }
        }
        return set;
    }
    return defValue;
}

5. CoverManager#setCoverRetrieversFromPreferences()

Project: dmix
Source File: CoverManager.java
View license
public void setCoverRetrieversFromPreferences() {
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(sApp);
    final List<CoverRetrievers> enabledRetrievers = new ArrayList<>();
    // Cache -> MPD Server -> LastFM
    if (settings.getBoolean(PREFERENCE_CACHE, true)) {
        enabledRetrievers.add(CoverRetrievers.CACHE);
    }
    if (!(settings.getBoolean(PREFERENCE_ONLY_WIFI, false)) | (isWifi())) {
        if (settings.getBoolean(PREFERENCE_LOCALSERVER, false)) {
            enabledRetrievers.add(CoverRetrievers.LOCAL);
        }
        if (settings.getBoolean(PREFERENCE_LASTFM, true)) {
            enabledRetrievers.add(CoverRetrievers.LASTFM);
            enabledRetrievers.add(CoverRetrievers.ITUNES);
            enabledRetrievers.add(CoverRetrievers.DEEZER);
            enabledRetrievers.add(CoverRetrievers.SPOTIFY);
            enabledRetrievers.add(CoverRetrievers.DISCOGS);
            enabledRetrievers.add(CoverRetrievers.GRACENOTE);
            enabledRetrievers.add(CoverRetrievers.MUSICBRAINZ);
        }
    }
    setCoverRetrievers(enabledRetrievers);
}

6. ArtistsFragment#onItemClick()

Project: dmix
Source File: ArtistsFragment.java
View license
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
    final AlbumsFragment af;
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mApp);
    if (settings.getBoolean(LibraryFragment.PREFERENCE_ALBUM_LIBRARY, true)) {
        af = new AlbumsGridFragment((Artist) mItems.get(position), mGenre);
    } else {
        af = new AlbumsFragment((Artist) mItems.get(position), mGenre);
    }
    ((ILibraryFragmentActivity) getActivity()).pushLibraryFragment(af, "album");
}

7. DashClockService#onCreate()

Project: dashclock
Source File: DashClockService.java
View license
@Override
public void onCreate() {
    super.onCreate();
    LOGD(TAG, "onCreate");
    // Initialize the extensions components (host and manager)
    mCallbacks = new CallbackList();
    mRegisteredCallbacks = new HashMap<>();
    mExtensionManager = ExtensionManager.getInstance(this);
    mExtensionManager.addOnChangeListener(this);
    mExtensionHost = new ExtensionHost(this);
    IntentFilter filter = new IntentFilter(ACTION_EXTENSION_UPDATE_REQUESTED);
    LocalBroadcastManager.getInstance(this).registerReceiver(mExtensionEventsReceiver, filter);
    // Start a periodic refresh of all the extensions
    // FIXME: only do this if there are any active extensions
    PeriodicExtensionRefreshReceiver.updateExtensionsAndEnsurePeriodicRefresh(this);
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sp.registerOnSharedPreferenceChangeListener(this);
    onSharedPreferenceChanged(sp, PREF_FORCE_WORLD_READABLE);
}

8. EventAppWidgetProvider#configureBackground()

View license
private void configureBackground(Context context, RemoteViews rv) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.getBoolean(PREF_SHOW_HEADER, true)) {
        rv.setViewVisibility(R.id.action_bar, View.VISIBLE);
    } else {
        rv.setViewVisibility(R.id.action_bar, View.GONE);
    }
    int color = prefs.getInt(PREF_BACKGROUND_COLOR, PREF_BACKGROUND_COLOR_DEFAULT);
    int opaqueColor = Color.rgb(red(color), green(color), blue(color));
    setColorFilter(rv, R.id.background_image, opaqueColor);
    setAlpha(rv, R.id.background_image, alpha(color));
}

9. SearchTutorialActivity#tryStartActivity()

View license
/**
     * Tries to start the activity. May do nothing if stored preferences
     * say to not show the tutorial again. Returns whether the tutorial
     * was actually started.
     */
/*package*/
static boolean tryStartActivity(final Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.getBoolean(PREF_DO_NOT_SHOW, false)) {
        return false;
    }
    Intent intent = new Intent(context, SearchTutorialActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(intent);
    return true;
}

10. Eula#shouldShowEula()

Project: astrid
Source File: Eula.java
View license
private boolean shouldShowEula(Activity activity) {
    if (Preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false))
        return false;
    //$NON-NLS-1$
    SharedPreferences p = activity.getSharedPreferences("eula", Activity.MODE_PRIVATE);
    if (p.getBoolean(PREFERENCE_EULA_ACCEPTED, false))
        return false;
    if (taskService.countTasks() > 0)
        return false;
    return true;
}

11. NotificationForwarder#onNotificationRemoved()

Project: APStatus
Source File: NotificationForwarder.java
View license
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
    String packageName = sbn.getPackageName();
    // ?? ??????????? ??????????? ?? ?????? ????, ????? ???????? ????????????
    if (packageName == null || packageName.equals(BuildConfig.APPLICATION_ID))
        return;
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (!preferences.getBoolean(Settings.PREF_SERVER_MODE, false))
        return;
    if (preferences.getBoolean(packageName, false)) {
        Intent intent = new Intent(this, Server.class);
        intent.setAction(Server.ACTION_REMOVE).putExtra(Server.EXTRA_PACKAGE, packageName).putExtra(Server.EXTRA_ID, sbn.getId());
        startService(intent);
    }
}

12. MainActivity#checkFirstLaunch()

Project: AntennaPod
Source File: MainActivity.java
View license
private void checkFirstLaunch() {
    SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    if (prefs.getBoolean(PREF_IS_FIRST_LAUNCH, true)) {
        new Handler().postDelayed(() -> drawerLayout.openDrawer(navDrawer), 1500);
        // for backward compatibility, we only change defaults for fresh installs
        UserPreferences.setUpdateInterval(12);
        SharedPreferences.Editor edit = prefs.edit();
        edit.putBoolean(PREF_IS_FIRST_LAUNCH, false);
        edit.commit();
    }
}

13. Themes#setThemeLegacy()

Project: Anki-Android
Source File: Themes.java
View license
public static void setThemeLegacy(Context context) {
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(context.getApplicationContext());
    if (prefs.getBoolean("invertedColors", false)) {
        int theme = Integer.parseInt(prefs.getString("nightTheme", "0"));
        switch(theme) {
            case THEME_NIGHT_DARK:
                context.setTheme(R.style.LegacyActionBarDark);
                break;
            case THEME_NIGHT_BLACK:
                context.setTheme(R.style.LegacyActionBarBlack);
                break;
        }
    } else {
        int theme = Integer.parseInt(prefs.getString("dayTheme", "0"));
        switch(theme) {
            case THEME_DAY_LIGHT:
                context.setTheme(R.style.LegacyActionBarLight);
                break;
            case THEME_DAY_PLAIN:
                context.setTheme(R.style.LegacyActionBarPlain);
                break;
        }
    }
}

14. Themes#setTheme()

Project: Anki-Android
Source File: Themes.java
View license
public static void setTheme(Context context) {
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(context.getApplicationContext());
    if (prefs.getBoolean("invertedColors", false)) {
        int theme = Integer.parseInt(prefs.getString("nightTheme", "0"));
        switch(theme) {
            case THEME_NIGHT_DARK:
                context.setTheme(R.style.Theme_Dark_Compat);
                break;
            case THEME_NIGHT_BLACK:
                context.setTheme(R.style.Theme_Black_Compat);
                break;
        }
    } else {
        int theme = Integer.parseInt(prefs.getString("dayTheme", "0"));
        switch(theme) {
            case THEME_DAY_LIGHT:
                context.setTheme(R.style.Theme_Light_Compat);
                break;
            case THEME_DAY_PLAIN:
                context.setTheme(R.style.Theme_Plain_Compat);
                break;
        }
    }
}

15. ChannelUtil#getChannelBySharedPreferences()

Project: AndroidStudyDemo
Source File: ChannelUtil.java
View license
/**
     * ?sp???channel
     * @param context
     * @return ?????????sp????????sp?????
     */
private static String getChannelBySharedPreferences(Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int currentVersionCode = getVersionCode(context);
    if (currentVersionCode == -1) {
        //????
        return "";
    }
    int versionCodeSaved = sp.getInt(CHANNEL_VERSION_KEY, -1);
    if (versionCodeSaved == -1) {
        //?????  ?? ?????????
        return "";
    }
    if (currentVersionCode != versionCodeSaved) {
        return "";
    }
    return sp.getString(CHANNEL_KEY, "");
}

16. ChannelUtil#getChannelBySharedPreferences()

View license
/**
	 * ?sp???channel
	 * @param context
	 * @return ?????????sp????????sp?????
	 */
private static String getChannelBySharedPreferences(Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int currentVersionCode = getVersionCode(context);
    if (currentVersionCode == -1) {
        //????
        return "";
    }
    int versionCodeSaved = sp.getInt(CHANNEL_VERSION_KEY, -1);
    if (versionCodeSaved == -1) {
        //?????  ?? ?????????
        return "";
    }
    if (currentVersionCode != versionCodeSaved) {
        return "";
    }
    return sp.getString(CHANNEL_KEY, "");
}

17. WatchFaceActivity#onResume()

View license
@Override
protected void onResume() {
    super.onResume();
    SharedPreferences pref = getSharedPreferences(SHARED_PREFERENCE, Context.MODE_PRIVATE);
    if (pref.contains(SettingsActivity.SHARED_PREFERENCE_SCHOOL)) {
        String schoolCode = pref.getString(SettingsActivity.SHARED_PREFERENCE_SCHOOL, "");
        loadSchoolWatchFace(schoolCode);
    } else {
        mBackground.setImageResource(R.drawable.bulldog_wallpaper);
        mClock.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        mContainer.setBackgroundColor(getResources().getColor(android.R.color.white));
    }
}

18. TvShowLibraryActivity#onGlobalLayout()

View license
public void onGlobalLayout() {
    mTabHost.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    String lastTab = "tab_tv";
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
    if (prefs.getBoolean(PREF_REMEMBER_TAB, false)) {
        lastTab = (getSharedPreferences("global", Context.MODE_PRIVATE).getString(LAST_TVSHOW_TAB_ID, "tab_tv"));
        mTabHost.selectTabByTag(lastTab);
    }
    initTab(lastTab);
}

19. MusicLibraryActivity#onGlobalLayout()

View license
public void onGlobalLayout() {
    mTabHost.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    String lastTab = "tab_albums";
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
    if (prefs.getBoolean(PREF_REMEMBER_TAB, false)) {
        lastTab = (getSharedPreferences("global", Context.MODE_PRIVATE).getString(LAST_MUSIC_TAB_ID, "tab_albums"));
        mTabHost.selectTabByTag(lastTab);
    }
    initTab(lastTab);
}

20. MovieLibraryActivity#onGlobalLayout()

View license
public void onGlobalLayout() {
    mTabHost.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    String lastTab = "tab_movies";
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
    if (prefs.getBoolean(PREF_REMEMBER_TAB, false)) {
        lastTab = (getSharedPreferences("global", Context.MODE_PRIVATE).getString(LAST_MOVIE_TAB_ID, "tab_movies"));
        mTabHost.selectTabByTag(lastTab);
    }
    initTab(lastTab);
}

21. Utils#checkDemoMode()

Project: android-proxy
Source File: Utils.java
View license
public static void checkDemoMode(Context ctx) {
    SharedPreferences prefs = ctx.getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_MULTI_PROCESS);
    if (prefs.getBoolean(Constants.PREFERENCES_DEMO_MODE, false)) {
        App.getInstance().demoMode = true;
    } else {
        App.getInstance().demoMode = false;
    }
}

22. UIUtils#SetProxyNotification()

Project: android-proxy
Source File: UIUtils.java
View license
/**
     * Notification related methods
     */
public static void SetProxyNotification(WiFiApConfig conf, Context callerContext) {
    SharedPreferences prefs = callerContext.getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_MULTI_PROCESS);
    if (prefs.getBoolean("preference_notification_enabled", false)) {
        String notificationTitle = ProxyUIUtils.GetStatusTitle(conf, callerContext);
        String notificationDescription = ProxyUIUtils.GetStatusDescription(conf, callerContext);
        // The PendingIntent will launch activity if the user selects this
        // notification
        Intent preferencesIntent = new Intent(callerContext, MasterActivity.class);
        EnableProxyNotification(callerContext, preferencesIntent, notificationTitle, notificationDescription);
    } else {
        DisableProxyNotification(callerContext);
    }
}

23. PasswordRepository#getRepositoryDirectory()

View license
public static File getRepositoryDirectory(Context context) {
    File dir = null;
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    if (settings.getBoolean("git_external", false)) {
        String external_repo = settings.getString("git_external_repo", null);
        if (external_repo != null) {
            dir = new File(external_repo);
        }
    } else {
        dir = new File(context.getFilesDir() + "/store");
    }
    return dir;
}

24. Prefs#remove()

Project: LinLock
Source File: Prefs.java
View license
/**
     * Removes a preference value.
     *
     * @param key The name of the preference to remove.
     * @see Editor#remove(String)
     */
public static void remove(final String key) {
    SharedPreferences prefs = getPreferences();
    final Editor editor = prefs.edit();
    if (prefs.contains(key + LENGTH)) {
        // Workaround for pre-HC's lack of StringSets
        int stringSetLength = prefs.getInt(key + LENGTH, -1);
        if (stringSetLength >= 0) {
            editor.remove(key + LENGTH);
            for (int i = 0; i < stringSetLength; i++) {
                editor.remove(key + "[" + i + "]");
            }
        }
    }
    editor.remove(key);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        editor.commit();
    } else {
        editor.apply();
    }
}

25. Prefs#getOrderedStringSet()

Project: LinLock
Source File: Prefs.java
View license
/**
     * Retrieves a Set of Strings as stored by {@link #putOrderedStringSet(String, Set)},
     * preserving the original order. Note that this implementation is heavier than the native
     * {@link #getStringSet(String, Set)} method (which does not guarantee to preserve order).
     *
     * @param key      The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference value if it exists, or defValues otherwise.
     * @throws ClassCastException if there is a preference with this name that is not a Set of
     *                            Strings.
     * @see #getStringSet(String, Set)
     */
public static Set<String> getOrderedStringSet(String key, final Set<String> defValue) {
    SharedPreferences prefs = getPreferences();
    if (prefs.contains(key + LENGTH)) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        int stringSetLength = prefs.getInt(key + LENGTH, -1);
        if (stringSetLength >= 0) {
            for (int i = 0; i < stringSetLength; i++) {
                set.add(prefs.getString(key + "[" + i + "]", null));
            }
        }
        return set;
    }
    return defValue;
}

26. SharedPreference#loadPreferencesData()

Project: IPTVFree
Source File: SharedPreference.java
View license
/**
     * Load saved preference.
     * @param context Context
     * @param KEY String
     * @return ArrayList<String>
     */
public ArrayList<String> loadPreferencesData(Context context, String KEY) {
    SharedPreferences settings;
    List<String> favorites;
    settings = context.getSharedPreferences(IPTV_PREFERENCES, Context.MODE_PRIVATE);
    if (settings.contains(KEY)) {
        String jsonFavorites = settings.getString(KEY, null);
        Gson gson = new Gson();
        String[] favoriteItems = gson.fromJson(jsonFavorites, String[].class);
        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<String>(favorites);
    } else
        return null;
    return new ArrayList<String>(favorites);
}

27. BaseActivity#onDestroy()

Project: iosched
Source File: BaseActivity.java
View license
@Override
protected void onDestroy() {
    super.onDestroy();
    if (mGCMRegisterTask != null) {
        LOGD(TAG, "Cancelling GCM registration task.");
        mGCMRegisterTask.cancel(true);
    }
    try {
        GCMRegistrar.onDestroy(this);
    } catch (Exception e) {
        LOGW(TAG, "C2DM unregistration error", e);
    }
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sp.unregisterOnSharedPreferenceChangeListener(this);
}

28. ExploreIOFragment#onAttach()

Project: iosched
Source File: ExploreIOFragment.java
View license
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // Register preference change listeners
    ConfMessageCardUtils.registerPreferencesChangeListener(getContext(), mConfMessagesAnswerChangeListener);
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
    sp.registerOnSharedPreferenceChangeListener(mSettingsChangeListener);
    // Register content observers
    mSessionsObserver = new ThrottledContentObserver(new ThrottledContentObserver.Callbacks() {

        @Override
        public void onThrottledContentObserverFired() {
            fireReloadEvent();
            fireReloadTagsEvent();
        }
    });
    mTagsObserver = new ThrottledContentObserver(new ThrottledContentObserver.Callbacks() {

        @Override
        public void onThrottledContentObserverFired() {
            fireReloadTagsEvent();
        }
    });
}

29. WPActivityUtils#applyLocale()

View license
public static void applyLocale(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (sharedPreferences.contains(AppSettingsFragment.LANGUAGE_PREF_KEY)) {
        Locale contextLocale = context.getResources().getConfiguration().locale;
        String contextLanguage = contextLocale.getLanguage();
        contextLanguage = LanguageUtils.patchDeviceLanguageCode(contextLanguage);
        String contextCountry = contextLocale.getCountry();
        String locale = sharedPreferences.getString(AppSettingsFragment.LANGUAGE_PREF_KEY, "");
        if (!TextUtils.isEmpty(contextCountry)) {
            contextLanguage += "-" + contextCountry;
        }
        if (!locale.equals(contextLanguage)) {
            Resources resources = context.getResources();
            Configuration conf = resources.getConfiguration();
            conf.locale = new Locale(locale);
            resources.updateConfiguration(conf, resources.getDisplayMetrics());
        }
    }
}

30. WifiReceiver#getScanPeriod()

View license
public long getScanPeriod() {
    final SharedPreferences prefs = mainActivity.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
    String scanPref = ListFragment.PREF_SCAN_PERIOD;
    long defaultRate = MainActivity.SCAN_DEFAULT;
    // if over 5 mph
    Location location = null;
    final GPSListener gpsListener = mainActivity.getGPSListener();
    if (gpsListener != null) {
        location = gpsListener.getLocation();
    }
    if (location != null && location.getSpeed() >= 2.2352f) {
        scanPref = ListFragment.PREF_SCAN_PERIOD_FAST;
        defaultRate = MainActivity.SCAN_FAST_DEFAULT;
    } else if (location == null || location.getSpeed() < 0.1f) {
        scanPref = ListFragment.PREF_SCAN_PERIOD_STILL;
        defaultRate = MainActivity.SCAN_STILL_DEFAULT;
    }
    return prefs.getLong(scanPref, defaultRate);
}

31. QKTextView#setText()

Project: qksms
Source File: QKTextView.java
View license
@Override
public void setText(CharSequence text, BufferType type) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    if (mType == FontManager.TEXT_TYPE_DIALOG_BUTTON) {
        text = text.toString().toUpperCase();
    }
    if (prefs.getBoolean(SettingsFragment.MARKDOWN_ENABLED, false)) {
        text = TextUtils.styleText(text);
        if (text == null || text.length() <= 0 || Build.VERSION.SDK_INT >= 19) {
            super.setText(text, BufferType.EDITABLE);
            return;
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        super.setText(builder, BufferType.EDITABLE);
    } else {
        super.setText(text, BufferType.NORMAL);
    }
}

32. EndlessJabberInterface#SendInfoToEndlessJabber()

Project: qksms
Source File: EndlessJabberInterface.java
View license
/**
	 * Refresh integration info with EndlessJabber
	 *
	 * @param ctx
	 *            Context to use
	 */
static void SendInfoToEndlessJabber(Context context) {
    String EndlessJabber_INTENT = "com.mariussoft.endlessjabber.action.extendResponse";
    SharedPreferences prefs = context.getSharedPreferences("EndlessJabberSDK", Context.MODE_PRIVATE);
    Intent i = new Intent();
    i.setAction(EndlessJabber_INTENT);
    i.putExtra("Action", "UpdateInfo");
    i.putExtra("PackageName", context.getPackageName());
    i.putExtra("Enabled", prefs.contains("InterfaceClass"));
    if (prefs.contains("InterfaceClass")) {
        i.putExtra("SendSMS", prefs.getBoolean("SendSMS", false));
        i.putExtra("SendMMS", prefs.getBoolean("SendMMS", false));
    }
    context.sendBroadcast(i);
}

33. PlumbleService#onDestroy()

Project: Plumble
Source File: PlumbleService.java
View license
@Override
public void onDestroy() {
    if (mNotification != null) {
        mNotification.hide();
        mNotification = null;
    }
    if (mReconnectNotification != null) {
        mReconnectNotification.hide();
        mReconnectNotification = null;
    }
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    preferences.unregisterOnSharedPreferenceChangeListener(this);
    try {
        unregisterReceiver(mTalkReceiver);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    unregisterObserver(mObserver);
    if (mTTS != null)
        mTTS.shutdown();
    mMessageLog = null;
    mMessageNotification.dismiss();
    super.onDestroy();
}

34. ChannelListFragment#onAttach()

Project: Plumble
Source File: ChannelListFragment.java
View license
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mTargetProvider = (ChatTargetProvider) getParentFragment();
    } catch (ClassCastException e) {
        throw new ClassCastException(getParentFragment().toString() + " must implement ChatTargetProvider");
    }
    try {
        mDatabaseProvider = (DatabaseProvider) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException(getActivity().toString() + " must implement DatabaseProvider");
    }
    mSettings = Settings.getInstance(activity);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
    preferences.registerOnSharedPreferenceChangeListener(this);
}

35. ChannelFragment#onActivityCreated()

Project: Plumble
Source File: ChannelFragment.java
View license
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    preferences.registerOnSharedPreferenceChangeListener(this);
    if (mViewPager != null) {
        // Phone
        ChannelFragmentPagerAdapter pagerAdapter = new ChannelFragmentPagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(pagerAdapter);
    } else {
        // Tablet
        ChannelListFragment listFragment = new ChannelListFragment();
        Bundle listArgs = new Bundle();
        listArgs.putBoolean("pinned", isShowingPinnedChannels());
        listFragment.setArguments(listArgs);
        ChannelChatFragment chatFragment = new ChannelChatFragment();
        getChildFragmentManager().beginTransaction().replace(R.id.list_fragment, listFragment).replace(R.id.chat_fragment, chatFragment).commit();
    }
}

36. ObscuraApp#onResume()

Project: ObscuraCam
Source File: ObscuraApp.java
View license
@Override
protected void onResume() {
    super.onResume();
    final SharedPreferences preferences = getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE);
    if (preferences.getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) {
    }
}

37. ActivityMain#isOldDonateVersionInstalled()

Project: NotePad
Source File: ActivityMain.java
View license
void isOldDonateVersionInstalled() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ActivityMain.this);
    if (prefs.getBoolean(MIGRATED, false)) {
        // already migrated
        return;
    }
    try {
        PackageManager pm = getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(0);
        for (ApplicationInfo packageInfo : packages) {
            if (packageInfo.packageName.equals("com.nononsenseapps.notepad_donate")) {
                migrateDonateUser();
                // Don't migrate again
                prefs.edit().putBoolean(MIGRATED, true).commit();
                // Stop loop
                break;
            }
        }
    } catch (Exception e) {
    }
}

38. App#onCreate()

Project: NewPipe
Source File: App.java
View license
@Override
public void onCreate() {
    super.onCreate();
    // Initialize image loader
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
    ImageLoader.getInstance().init(config);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean(getString(R.string.use_tor_key), false)) {
        OrbotHelper.requestStartTor(this);
        configureTor(true);
    } else {
        configureTor(false);
    }
    // DO NOT REMOVE THIS FUNCTION!!!
    // Otherwise downloadPathPreference has invalid value.
    SettingsActivity.initSettings(this);
}

39. FsPreferenceActivity#onResume()

Project: swiftp
Source File: FsPreferenceActivity.java
View license
@Override
protected void onResume() {
    super.onResume();
    updateRunningState();
    Log.d(TAG, "onResume: Register the preference change listner");
    SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
    sp.registerOnSharedPreferenceChangeListener(this);
    Log.d(TAG, "onResume: Registering the FTP server actions");
    IntentFilter filter = new IntentFilter();
    filter.addAction(FsService.ACTION_STARTED);
    filter.addAction(FsService.ACTION_STOPPED);
    filter.addAction(FsService.ACTION_FAILEDTOSTART);
    registerReceiver(mFsActionsReceiver, filter);
}

40. SeasonsFragment#onActivityCreated()

Project: SeriesGuide
Source File: SeasonsFragment.java
View license
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getPreferences();
    // populate list
    mAdapter = new SeasonsAdapter(getActivity(), this);
    setListAdapter(mAdapter);
    // now let's get a loader or reconnect to existing one
    getLoaderManager().initLoader(OverviewActivity.SEASONS_LOADER_ID, null, this);
    // listen to changes to the sorting preference
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    prefs.registerOnSharedPreferenceChangeListener(mPrefsListener);
    registerForContextMenu(getListView());
    setHasOptionsMenu(true);
}

41. DisplayUtils#overscanCompensation()

Project: serenity-android
Source File: DisplayUtils.java
View license
public static void overscanCompensation(Context context, View... views) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.getBoolean("overscan_compensation", false)) {
        for (View view : views) {
            if (view != null) {
                // ViewGroup.MarginLayoutParams params =
                // (ViewGroup.MarginLayoutParams) view
                // .getLayoutParams();
                view.setPadding(prefs.getInt("overscan_left", 50), prefs.getInt("overscan_top", 50), prefs.getInt("overscan_right", 50), prefs.getInt("overscan_bottom", 50));
            // params.setMargins(prefs.getInt("overscan_left", 50),
            // prefs.getInt("overscan_top", 50),
            // prefs.getInt("overscan_right", 50),
            // prefs.getInt("overscan_bottom", 50));
            }
        }
    }
}

42. ObscuredPreferencesBuilder#createSharedPrefs()

View license
public SharedPreferences createSharedPrefs() {
    SharedPreferences sharedPrefDelegate = application.getSharedPreferences(sharedPrefFileName, Context.MODE_PRIVATE);
    SharedPreferences sharedPreferences;
    if (isObfuscated || isKeyObfuscated) {
        sharedPreferences = new ObscuredSharedPreferences(application, sharedPrefDelegate, isKeyObfuscated);
        if (!TextUtils.isEmpty(this.secret)) {
            ((ObscuredSharedPreferences) sharedPreferences).setSecret(secret);
        } else {
            Log.d("SharedPrefsBuilder", "secret is empty");
        }
    } else {
        sharedPreferences = sharedPrefDelegate;
    }
    return sharedPreferences;
}

43. StartActivity#prepareWorkout()

Project: runnerup
Source File: StartActivity.java
View license
Workout prepareWorkout() {
    Context ctx = getApplicationContext();
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
    SharedPreferences audioPref = null;
    Workout w = null;
    if (tabHost.getCurrentTabTag().contentEquals(TAB_BASIC)) {
        audioPref = WorkoutBuilder.getAudioCuePreferences(ctx, pref, getString(R.string.pref_basic_audio));
        Dimension target = Dimension.valueOf(simpleTargetType.getValueInt());
        w = WorkoutBuilder.createDefaultWorkout(getResources(), pref, target);
    } else if (tabHost.getCurrentTabTag().contentEquals(TAB_INTERVAL)) {
        audioPref = WorkoutBuilder.getAudioCuePreferences(ctx, pref, getString(R.string.pref_interval_audio));
        w = WorkoutBuilder.createDefaultIntervalWorkout(getResources(), pref);
    } else if (tabHost.getCurrentTabTag().contentEquals(TAB_ADVANCED)) {
        audioPref = WorkoutBuilder.getAudioCuePreferences(ctx, pref, getString(R.string.pref_advanced_audio));
        w = advancedWorkout;
    }
    WorkoutBuilder.prepareWorkout(getResources(), pref, w, TAB_BASIC.contentEquals(tabHost.getCurrentTabTag()));
    WorkoutBuilder.addAudioCuesToWorkout(getResources(), w, audioPref);
    return w;
}

44. RunKeeperSynchronizer#getLapLength()

Project: runnerup
Source File: RunKeeperSynchronizer.java
View license
private double getLapLength() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Resources res = context.getResources();
    double lapLength = Formatter.getUnitMeters(context);
    if (prefs.getBoolean(res.getString(R.string.pref_autolap_active), false)) {
        String autoLap = prefs.getString(res.getString(R.string.pref_autolap), String.valueOf(lapLength));
        try {
            lapLength = Double.parseDouble(autoLap);
        } catch (NumberFormatException e) {
            return lapLength;
        }
        return lapLength;
    }
    return lapLength;
}

45. MainActivity#onCreate()

Project: Roundr
Source File: MainActivity.java
View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!BootReceiver.boot_up || Corner.running) {
        Intent i = new Intent(this, SettingsActivity.class);
        startActivity(i);
    }
    if (prefs.getBoolean("enable", true)) {
        StandOutWindow.show(this, Corner.class, 0);
        StandOutWindow.show(this, Corner.class, 1);
        StandOutWindow.show(this, Corner.class, 2);
        StandOutWindow.show(this, Corner.class, 3);
    }
    finish();
}

46. ServiceSinkhole#prepareForwarding()

Project: NetGuard
Source File: ServiceSinkhole.java
View license
private void prepareForwarding() {
    mapForward.clear();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean("filter", false)) {
        Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getForwarding();
        int colProtocol = cursor.getColumnIndex("protocol");
        int colDPort = cursor.getColumnIndex("dport");
        int colRAddr = cursor.getColumnIndex("raddr");
        int colRPort = cursor.getColumnIndex("rport");
        int colRUid = cursor.getColumnIndex("ruid");
        while (cursor.moveToNext()) {
            Forward fwd = new Forward();
            fwd.protocol = cursor.getInt(colProtocol);
            fwd.dport = cursor.getInt(colDPort);
            fwd.raddr = cursor.getString(colRAddr);
            fwd.rport = cursor.getInt(colRPort);
            fwd.ruid = cursor.getInt(colRUid);
            mapForward.put(fwd.dport, fwd);
            Log.i(TAG, "Forward " + fwd);
        }
        cursor.close();
    }
}

47. ActivitySettings#onPause()

Project: NetGuard
Source File: ActivitySettings.java
View license
@Override
protected void onPause() {
    super.onPause();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);
    unregisterReceiver(interactiveStateReceiver);
    unregisterReceiver(connectivityChangedReceiver);
    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        phone_state = false;
    }
}

48. MainActivity#onStart()

Project: Minimal-Todo
Source File: MainActivity.java
View license
@Override
protected void onStart() {
    app = (AnalyticsApplication) getApplication();
    super.onStart();
    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DATA_SET_CHANGED, MODE_PRIVATE);
    if (sharedPreferences.getBoolean(CHANGE_OCCURED, false)) {
        mToDoItemsArrayList = getLocallyStoredData(storeRetrieveData);
        adapter = new BasicListAdapter(mToDoItemsArrayList);
        mRecyclerView.setAdapter(adapter);
        setAlarms();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(CHANGE_OCCURED, false);
        //            editor.commit();
        editor.apply();
    }
}

49. MainActivity#onCreate()

View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Prefs.init(this);
    findViewById(R.id.pref_form).setOnClickListener(this);
    findViewById(R.id.pref_configs).setOnClickListener(this);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);
    setUserInputModule(prefs.getBoolean(Prefs.keys().KEY_USE_LOVELY, false));
}

50. LocalIMEKeyboard#getOverrideFonts()

View license
@Override
public boolean getOverrideFonts() {
    SharedPreferences prefs;
    if (!canOverrideFonts())
        return false;
    prefs = PreferenceManager.getDefaultSharedPreferences(wav);
    return prefs.getBoolean(PREF_FONT_OVERRIDE, false);
}

51. VLCOptions#getEqualizer()

Project: VCL-Android
Source File: VLCOptions.java
View license
@MainThread
public static MediaPlayer.Equalizer getEqualizer(Context context) {
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    if (pref.getBoolean("equalizer_enabled", false)) {
        final float[] bands = Preferences.getFloatArray(pref, "equalizer_values");
        final int bandCount = MediaPlayer.Equalizer.getBandCount();
        if (bands.length != bandCount + 1)
            return null;
        final MediaPlayer.Equalizer eq = MediaPlayer.Equalizer.create();
        eq.setPreAmp(bands[0]);
        for (int i = 0; i < bandCount; ++i) eq.setAmp(i, bands[i + 1]);
        return eq;
    } else
        return null;
}

52. PlaybackActivity#onStart()

Project: vanilla
Source File: PlaybackActivity.java
View license
@Override
public void onStart() {
    super.onStart();
    if (PlaybackService.hasInstance())
        onServiceReady();
    else
        startService(new Intent(this, PlaybackService.class));
    SharedPreferences prefs = PlaybackService.getSettings(this);
    mUpAction = Action.getAction(prefs, PrefKeys.SWIPE_UP_ACTION, PrefDefaults.SWIPE_UP_ACTION);
    mDownAction = Action.getAction(prefs, PrefKeys.SWIPE_DOWN_ACTION, PrefDefaults.SWIPE_DOWN_ACTION);
    Window window = getWindow();
    if (prefs.getBoolean(PrefKeys.DISABLE_LOCKSCREEN, PrefDefaults.DISABLE_LOCKSCREEN))
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    else
        window.clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}

53. ChannelUtil#getChannelBySharedPreferences()

Project: TLint
Source File: ChannelUtil.java
View license
/**
   * ?sp???channel
   *
   * @return ?????????sp????????sp?????
   */
private static String getChannelBySharedPreferences(Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int currentVersionCode = getVersionCode(context);
    if (currentVersionCode == -1) {
        //????
        return "";
    }
    int versionCodeSaved = sp.getInt(CHANNEL_VERSION_KEY, -1);
    if (versionCodeSaved == -1) {
        //?????  ?? ?????????
        return "";
    }
    if (currentVersionCode != versionCodeSaved) {
        return "";
    }
    return sp.getString(CHANNEL_KEY, "");
}

54. SyncthingService#onDestroy()

View license
/**
     * Stops the native binary.
     *
     * The native binary crashes if stopped before it is fully active. In that case signal the
     * stop request to PollWebGuiAvailableTaskImpl that is active in that situation and terminate
     * the service there.
     */
@Override
public void onDestroy() {
    synchronized (stateLock) {
        if (mCurrentState == State.INIT || mCurrentState == State.STARTING) {
            Log.i(TAG, "Delay shutting down service until initialisation of Syncthing finished");
            mStopScheduled = true;
        } else {
            Log.i(TAG, "Shutting down service immediately");
            shutdown();
        }
    }
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sp.unregisterOnSharedPreferenceChangeListener(this);
}

55. App#initializeGa()

Project: iFixitAndroid
Source File: App.java
View license
/*
    * Method to handle basic Google Analytics initialization. This call will not
    * block as all Google Analytics work occurs off the main thread.
    */
private void initializeGa() {
    GoogleAnalytics ga = GoogleAnalytics.getInstance(this);
    mGaTracker = ga.getTracker(BuildConfig.GA_PROPERTY_ID);
    GAServiceManager.getInstance().setLocalDispatchPeriod(GA_DISPATCH_PERIOD);
    // Set dryRun to disable event dispatching.
    ga.setDryRun(BuildConfig.DEBUG);
    ga.getLogger().setLogLevel(BuildConfig.DEBUG ? Logger.LogLevel.INFO : Logger.LogLevel.WARNING);
    // Set the opt out flag when user updates a tracking preference.
    SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals(TRACKING_PREF_KEY)) {
                GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, false));
            }
        }
    });
}

56. TimeZoneListener#onReceive()

Project: Pedometer
Source File: TimeZoneListener.java
View license
@Override
public void onReceive(final Context context, final Intent intent) {
    SharedPreferences prefs = context.getSharedPreferences("pedometer", Context.MODE_MULTI_PROCESS);
    TimeZone oldTimeZone = TimeZone.getTimeZone(prefs.getString("timezone", TimeZone.getDefault().getID()));
    TimeZone newTimeZone = TimeZone.getTimeZone(intent.getStringExtra("time-zone"));
    if (BuildConfig.DEBUG) {
        Logger.log("timezone changed: new: " + newTimeZone.getRawOffset() + " old: " + oldTimeZone.getRawOffset());
        Logger.log("Today: " + Util.getToday());
    }
    Database db = Database.getInstance(context);
    db.timeZoneChanged(newTimeZone.getRawOffset() - oldTimeZone.getRawOffset());
    db.close();
    prefs.edit().putString("timezone", intent.getStringExtra("time-zone")).commit();
}

57. PowerReceiver#onReceive()

Project: Pedometer
Source File: PowerReceiver.java
View license
@Override
public void onReceive(final Context context, final Intent intent) {
    SharedPreferences prefs = context.getSharedPreferences("pedometer", Context.MODE_MULTI_PROCESS);
    if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction()) && !prefs.contains("pauseCount")) {
        // if power connected & not already paused, then pause now
        context.startService(new Intent(context, SensorListener.class).putExtra("action", SensorListener.ACTION_PAUSE));
    } else if (Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction()) && prefs.contains("pauseCount")) {
        // if power disconnected & currently paused, then resume now
        context.startService(new Intent(context, SensorListener.class).putExtra("action", SensorListener.ACTION_PAUSE));
    }
}

58. Configuration#getLastIndex()

Project: PageTurner
Source File: Configuration.java
View license
public int getLastIndex(String fileName) {
    SharedPreferences bookPrefs = getPrefsForBook(fileName);
    int pos = bookPrefs.getInt(KEY_IDX, -1);
    if (pos != -1) {
        return pos;
    }
    //Fall-backs to older setting in central file
    String bookHash = Integer.toHexString(fileName.hashCode());
    pos = settings.getInt(KEY_IDX + bookHash, -1);
    if (pos != -1) {
        return pos;
    }
    // Fall-back for even older settings.
    return settings.getInt(KEY_IDX + fileName, -1);
}

59. Configuration#getPageOffsets()

Project: PageTurner
Source File: Configuration.java
View license
public Option<List<List<Integer>>> getPageOffsets(String fileName) {
    SharedPreferences bookPrefs = getPrefsForBook(fileName);
    String data = bookPrefs.getString(KEY_OFFSETS, "");
    if (data.length() == 0) {
        return none();
    }
    try {
        PageOffsets offsets = PageOffsets.fromJSON(data);
        if (offsets == null || !offsets.isValid(this)) {
            return none();
        }
        return option(offsets.getOffsets());
    } catch (JSONException js) {
        LOG.error("Could not retrieve page offsets", js);
        return none();
    }
}

60. Configuration#setPageOffsets()

Project: PageTurner
Source File: Configuration.java
View license
public void setPageOffsets(String fileName, List<List<Integer>> offsets) {
    SharedPreferences bookPrefs = getPrefsForBook(fileName);
    PageOffsets offsetsObject = PageOffsets.fromValues(this, offsets);
    try {
        String json = offsetsObject.toJSON();
        updateValue(bookPrefs, KEY_OFFSETS, json);
    } catch (JSONException js) {
        LOG.error("Error storing page offsets", js);
    }
}

61. Configuration#getLastPosition()

Project: PageTurner
Source File: Configuration.java
View license
public int getLastPosition(String fileName) {
    SharedPreferences bookPrefs = getPrefsForBook(fileName);
    int pos = bookPrefs.getInt(KEY_POS, -1);
    if (pos != -1) {
        return pos;
    }
    //Fall-back to older settings
    String bookHash = Integer.toHexString(fileName.hashCode());
    pos = settings.getInt(KEY_POS + bookHash, -1);
    if (pos != -1) {
        return pos;
    }
    // Fall-back for even older settings.
    return settings.getInt(KEY_POS + fileName, -1);
}

62. OpenStreetMapUpload#startUpload()

View license
/**
	 * Either starts uploading directly if we are authenticated against OpenStreetMap,
	 * or ask the user to authenticate via the browser.
	 */
private void startUpload() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.contains(OSMTracker.Preferences.KEY_OSM_OAUTH_TOKEN) && prefs.contains(OSMTracker.Preferences.KEY_OSM_OAUTH_SECRET)) {
        // Re-use saved token
        oAuthConsumer.setTokenWithSecret(prefs.getString(OSMTracker.Preferences.KEY_OSM_OAUTH_TOKEN, ""), prefs.getString(OSMTracker.Preferences.KEY_OSM_OAUTH_SECRET, ""));
        uploadToOsm();
    } else {
        // Open browser and request token
        new RetrieveRequestTokenTask(this, oAuthProvider, oAuthConsumer, OAUTH_CALLBACK_URL + trackId).execute();
    }
}

63. CloudmadeUtil#retrieveCloudmadeKey()

Project: osmdroid
Source File: CloudmadeUtil.java
View license
/**
	 * Retrieve the key from the manifest and store it for later use.
	 */
public static void retrieveCloudmadeKey(final Context aContext) {
    mAndroidId = Settings.Secure.getString(aContext.getContentResolver(), Settings.Secure.ANDROID_ID);
    // get the key from the manifest
    mKey = ManifestUtil.retrieveKey(aContext, CLOUDMADE_KEY);
    // if the id hasn't changed then set the token to the previous token
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(aContext);
    mPreferenceEditor = pref.edit();
    final String id = pref.getString(CLOUDMADE_ID, "");
    if (id.equals(mAndroidId)) {
        mToken = pref.getString(CLOUDMADE_TOKEN, "");
        // if we've got a token we don't need the editor any more
        if (mToken.length() > 0) {
            mPreferenceEditor = null;
        }
    } else {
        mPreferenceEditor.putString(CLOUDMADE_ID, mAndroidId);
        mPreferenceEditor.commit();
    }
}

64. StartSharingActivity#saveAndFinish()

View license
protected void saveAndFinish() {
    String nickname = eNickName.getText().toString();
    String group = eGroup.getText().toString();
    String message = eMessage.getText().toString();
    //Keep in prefs
    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    SharedPreferences.Editor editor = SP.edit();
    editor.putString("NICKNAME", nickname);
    editor.putString("GROUP", group);
    editor.commit();
    Intent intent = new Intent();
    intent.putExtra("NICKNAME", nickname);
    intent.putExtra("GROUP", group);
    intent.putExtra("MESSAGE", message);
    setResult(RESULT_OK, intent);
    finish();
}

65. StartSharingActivity#onCreate()

View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_sharing);
    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    eNickName = (EditText) findViewById(R.id.nickname);
    eNickName.setText(SP.getString("NICKNAME", ""));
    eGroup = (EditText) findViewById(R.id.group);
    eGroup.setText(SP.getString("GROUP", ""));
    eMessage = (EditText) findViewById(R.id.message);
    Button btnOk = (Button) findViewById(R.id.btnOK);
    btnOk.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            saveAndFinish();
        }
    });
}

66. MapActivity#savePrefs()

Project: osmbonuspack
Source File: MapActivity.java
View license
//---
void savePrefs() {
    SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE);
    SharedPreferences.Editor ed = prefs.edit();
    ed.putInt("MAP_ZOOM_LEVEL", map.getZoomLevel());
    GeoPoint c = (GeoPoint) map.getMapCenter();
    ed.putFloat("MAP_CENTER_LAT", (float) c.getLatitude());
    ed.putFloat("MAP_CENTER_LON", (float) c.getLongitude());
    View searchPanel = (View) findViewById(R.id.search_panel);
    ed.putInt("PANEL_VISIBILITY", searchPanel.getVisibility());
    MapTileProviderBase tileProvider = map.getTileProvider();
    String tileProviderName = tileProvider.getTileSource().name();
    ed.putString("TILE_PROVIDER", tileProviderName);
    ed.putInt("ROUTE_PROVIDER", mWhichRouteProvider);
    ed.commit();
}

67. AutoCompleteOnPreferences#getPreferences()

View license
protected String[] getPreferences() {
    SharedPreferences prefs = getContext().getSharedPreferences(mAppKey, Context.MODE_PRIVATE);
    String prefString = prefs.getString(mKey, "[]");
    try {
        JSONArray prefArray = new JSONArray(prefString);
        String[] result = new String[prefArray.length()];
        for (int i = 0; i < prefArray.length(); i++) {
            result[i] = prefArray.getString(i);
        }
        return result;
    } catch (JSONException e) {
        e.printStackTrace();
        return new String[0];
    }
}

68. DeviceManager#getLastConnectedDevice()

Project: openxc-android
Source File: DeviceManager.java
View license
public BluetoothDevice getLastConnectedDevice() {
    SharedPreferences preferences = mContext.getSharedPreferences(KNOWN_BLUETOOTH_DEVICE_PREFERENCES, Context.MODE_MULTI_PROCESS);
    String lastConnectedDeviceAddress = preferences.getString(LAST_CONNECTED_BLUETOOTH_DEVICE_PREF_KEY, null);
    BluetoothDevice lastConnectedDevice = null;
    if (lastConnectedDeviceAddress != null) {
        lastConnectedDevice = getDefaultAdapter().getRemoteDevice(lastConnectedDeviceAddress);
    }
    return lastConnectedDevice;
}

69. SettingsActivity#initializeNetwork()

View license
protected void initializeNetwork(PreferenceManager manager) {
    mNetworkHostPreference = (EditTextPreference) manager.findPreference(getString(R.string.network_host_key));
    mNetworkHostPreference.setOnPreferenceChangeListener(mUpdateSummaryListener);
    mNetworkPortPreference = (EditTextPreference) manager.findPreference(getString(R.string.network_port_key));
    mNetworkPortPreference.setOnPreferenceChangeListener(mUpdateSummaryListener);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    updateSummary(mNetworkHostPreference, preferences.getString(getString(R.string.network_host_key), null));
    updateSummary(mNetworkPortPreference, preferences.getString(getString(R.string.network_port_key), null));
}

70. SettingsActivity#initializeUploadingPreferences()

View license
protected void initializeUploadingPreferences(PreferenceManager manager) {
    mUploadingPreference = (CheckBoxPreference) manager.findPreference(getString(R.string.uploading_checkbox_key));
    Preference uploadingPathPreference = manager.findPreference(getString(R.string.uploading_path_key));
    uploadingPathPreference.setOnPreferenceChangeListener(mUploadingPathPreferenceListener);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    updateSummary(uploadingPathPreference, preferences.getString(getString(R.string.uploading_path_key), null));
}

71. SettingsActivity#initializeTracePreferences()

View license
protected void initializeTracePreferences(PreferenceManager manager) {
    mTraceFilePreference = manager.findPreference(getString(R.string.trace_source_file_key));
    mTraceFilePreference.setOnPreferenceClickListener(mTraceFileClickListener);
    mTraceFilePreference.setOnPreferenceChangeListener(mUpdateSummaryListener);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    updateSummary(mTraceFilePreference, preferences.getString(getString(R.string.trace_source_file_key), null));
}

72. MainActivity#buildPath()

View license
public String buildPath(Context context) {
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String arch = mySharedPreferences.getString("prefArch", "arm64");
    String base = mySharedPreferences.getString("prefBase", getString(R.string.base_val)).trim();
    Uri builtUri = Uri.parse(base).buildUpon().appendPath(getString(R.string.subdir)).appendPath(arch).appendPath("releases").build();
    return builtUri.toString();
}

73. MainActivity#setRecurringAlarm()

View license
public void setRecurringAlarm(Context context) {
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    int hour = Integer.parseInt(mySharedPreferences.getString("prefHour", getString(R.string.hour_val)));
    int minute = Integer.parseInt(mySharedPreferences.getString("prefMinute", getString(R.string.minute_val)));
    Calendar updateTime = Calendar.getInstance();
    //updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
    updateTime.set(Calendar.HOUR_OF_DAY, hour);
    updateTime.set(Calendar.MINUTE, minute);
    Intent downloader = new Intent(context, AlarmReceiver.class);
    PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}

74. DirectoryPicker#returnDir()

View license
private void returnDir(String path) {
    String base = Environment.getExternalStorageDirectory().getAbsolutePath();
    if (path.contains(base)) {
        path = path.substring(base.length(), path.length());
    }
    Intent result = new Intent();
    result.putExtra(CHOSEN_DIRECTORY, path);
    setResult(RESULT_OK, result);
    Log.d("basketbuilddownloader", "chose: " + path);
    Context context = getApplicationContext();
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor prefEdit = mySharedPreferences.edit();
    prefEdit.remove("prefDirectory");
    prefEdit.putString("prefDirectory", path);
    prefEdit.apply();
    finish();
}

75. BootReceiver#setRecurringAlarm()

View license
public void setRecurringAlarm(Context context) {
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    int hour = Integer.parseInt(mySharedPreferences.getString("prefHour", context.getString(R.string.hour_val)));
    int minute = Integer.parseInt(mySharedPreferences.getString("prefMinute", context.getString(R.string.minute_val)));
    Calendar updateTime = Calendar.getInstance();
    //updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
    updateTime.set(Calendar.HOUR_OF_DAY, hour);
    updateTime.set(Calendar.MINUTE, minute);
    Intent downloader = new Intent(context, AlarmReceiver.class);
    PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}

76. AlarmReceiver#buildPath()

View license
public String buildPath(Context context) {
    SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String arch = mySharedPreferences.getString("prefArch", "arm64");
    String base = mySharedPreferences.getString("prefBase", "").trim();
    Uri builtUri = Uri.parse(base).buildUpon().appendPath("opengapps").appendPath(arch).appendPath("releases").build();
    return builtUri.toString();
}

77. BackwardsCompatibilityTests#backwardsCompatibilityWithPre1Versions()

View license
@Test
public void backwardsCompatibilityWithPre1Versions() {
    String tag = "version 0.5 tag";
    SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(PersistedMap.class.getSimpleName() + "TagLastSeenMap", Context.MODE_PRIVATE);
    sharedPreferences.edit().putLong(tag, 1234L).apply();
    Once.initialise(RuntimeEnvironment.application);
    Once.markDone(tag);
    Assert.assertTrue(Once.beenDone(tag, exactly(2)));
}

78. VideoEditor#setPrefs()

Project: ObscuraCam
Source File: VideoEditor.java
View license
private void setPrefs() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    eyesOnly = prefs.getBoolean("pref_eyes_only", false);
    outFrameRate = Integer.parseInt(prefs.getString("pref_out_fps", DEFAULT_OUT_FPS).trim());
    outBitRate = Integer.parseInt(prefs.getString("pref_out_rate", DEFAULT_OUT_RATE).trim());
    outFormat = prefs.getString("pref_out_format", DEFAULT_OUT_FORMAT).trim();
    outAcodec = prefs.getString("pref_out_acodec", DEFAULT_OUT_ACODEC).trim();
    outVcodec = prefs.getString("pref_out_vcodec", DEFAULT_OUT_VCODEC).trim();
    outVWidth = Integer.parseInt(prefs.getString("pref_out_vwidth", DEFAULT_OUT_WIDTH).trim());
    outVHeight = Integer.parseInt(prefs.getString("pref_out_vheight", DEFAULT_OUT_HEIGHT).trim());
}

79. FFMPEGWrapper#checkBinary()

Project: ObscuraCam
Source File: FFMPEGWrapper.java
View license
private void checkBinary() throws FileNotFoundException, IOException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String currTorBinary = prefs.getString(FFMPEG_VERSION_KEY, null);
    if ((currTorBinary == null || (!currTorBinary.equals(FFMPEG_BINARY_VERSION))) || !new File(fileBinDir, libraryAssets[0]).exists()) {
        BinaryInstaller bi = new BinaryInstaller(context, fileBinDir);
        bi.installFromRaw();
    }
}

80. WallpaperFactory#getPrefSystemWallpaper()

View license
/**
     * Create a bitmap that is blurred and dimmed with the amount that user has selected.
     *
     * @return Background bitmap.
     */
public Bitmap getPrefSystemWallpaper() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    float radius = preferences.getFloat(PreferenceKeys.PREF_RADIUS, ImageBlurrer.MAX_SUPPORTED_BLUR_PIXELS);
    int dim = preferences.getInt(PreferenceKeys.PREF_DIM, DEFAULT_MAX_DIM);
    DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
    // Blur
    ImageBlurrer imageBlurrer = new ImageBlurrer(mContext);
    Bitmap blurred = imageBlurrer.blurBitmap(drawableToBitmap(mWallpaperManager.getFastDrawable(), displayMetrics.widthPixels), radius);
    // Dim
    Canvas c = new Canvas(blurred);
    c.drawColor(Color.argb(255 - dim, 0, 0, 0));
    return blurred;
}

81. AppearanceSettingsFragment#onItemSelected()

View license
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // selected, so we use this boolean value to work it around.
    if (mNothingSelected) {
        mNothingSelected = false;
        return;
    }
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    if (position == 0) {
        pref.edit().putInt(PreferenceKeys.PREF_BACKGROUND, WallpaperFactory.BACKGROUND_PURE_BLACK).apply();
    } else {
        pref.edit().putInt(PreferenceKeys.PREF_BACKGROUND, WallpaperFactory.BACKGROUND_SYSTEM_WALLPAPER).apply();
    }
    mHandler.postDelayed(mChangePreviewRunnable, 300);
}

82. AppearanceSettingsFragment#initSeekBars()

View license
private void initSeekBars() {
    mRadiusSeek.setMax(ImageBlurrer.MAX_SUPPORTED_BLUR_PIXELS * 10);
    mDimSeek.setMax(WallpaperFactory.DEFAULT_MAX_DIM);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    int radius = (int) (preferences.getFloat(PreferenceKeys.PREF_RADIUS, ImageBlurrer.MAX_SUPPORTED_BLUR_PIXELS) * 10);
    int dim = preferences.getInt(PreferenceKeys.PREF_DIM, WallpaperFactory.DEFAULT_MAX_DIM);
    mRadiusSeek.setProgress(radius);
    mDimSeek.setProgress(255 - dim);
    mRadiusSeek.setOnSeekBarChangeListener(this);
    mDimSeek.setOnSeekBarChangeListener(this);
}

83. NotificationService#onCreate()

View license
@Override
public void onCreate() {
    super.onCreate();
    mNotificationHub = NotificationHub.getInstance();
    mNotificationPeek = new NotificationPeek(mNotificationHub, this);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    // Retrieve user specified peek timeout.
    mPeekTimeoutMultiplier = Integer.parseInt(preferences.getString(PreferenceKeys.PREF_PEEK_TIMEOUT, "1"));
    // Does user select always listening?
    mSensorTimeoutMultiplier = Integer.parseInt(preferences.getString(PreferenceKeys.PREF_SENSOR_TIMEOUT, "1"));
    // Does user select always show content?
    mShowContent = preferences.getBoolean(PreferenceKeys.PREF_ALWAYS_SHOW_CONTENT, false);
    mAppList = AppList.getInstance(this);
    registerNotificationActionReceiver();
}

84. Widget#update()

Project: NetGuard
Source File: Widget.java
View license
private static void update(int[] appWidgetIds, AppWidgetManager appWidgetManager, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean enabled = prefs.getBoolean("enabled", false);
    try {
        try {
            PendingIntent pi;
            if (VpnService.prepare(context) == null)
                pi = PendingIntent.getBroadcast(context, 0, new Intent(enabled ? INTENT_OFF : INTENT_ON), PendingIntent.FLAG_UPDATE_CURRENT);
            else
                pi = PendingIntent.getActivity(context, 0, new Intent(context, ActivityMain.class), PendingIntent.FLAG_UPDATE_CURRENT);
            for (int id : appWidgetIds) {
                RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
                views.setOnClickPendingIntent(R.id.ivEnabled, pi);
                views.setImageViewResource(R.id.ivEnabled, enabled ? R.mipmap.ic_launcher : R.drawable.ic_security_white_24dp_60);
                appWidgetManager.updateAppWidget(id, views);
            }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}

85. PlaybackService#newMediaPlayer()

Project: VCL-Android
Source File: PlaybackService.java
View license
private MediaPlayer newMediaPlayer() {
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    final MediaPlayer mp = new MediaPlayer(LibVLC());
    final String aout = VLCOptions.getAout(pref);
    if (mp.setAudioOutput(aout) && aout.equals("android_audiotrack")) {
        mIsAudioTrack = true;
        if (mHasHdmiAudio)
            mp.setAudioOutputDevice("hdmi");
    } else
        mIsAudioTrack = false;
    mp.getVLCVout().addCallback(this);
    return mp;
}

86. WidgetSettings#isLightTheme()

Project: SeriesGuide
Source File: WidgetSettings.java
View license
/**
     * Returns if this widget should use a light theme instead of the default one.
     */
public static boolean isLightTheme(Context context, int appWidgetId) {
    SharedPreferences prefs = context.getSharedPreferences(SETTINGS_FILE, 0);
    boolean isLightTheme = false;
    try {
        isLightTheme = Integer.parseInt(prefs.getString(KEY_PREFIX_WIDGET_THEME + appWidgetId, "0")) == 1;
    } catch (NumberFormatException ignored) {
    }
    return isLightTheme;
}

87. PlaybackService#loadLastPlaylist()

Project: VCL-Android
Source File: PlaybackService.java
View license
private synchronized void loadLastPlaylist() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String currentMedia = prefs.getString("current_media", "");
    if (currentMedia.equals(""))
        return;
    String[] locations = prefs.getString("media_list", "").split(" ");
    List<String> mediaPathList = new ArrayList<String>(locations.length);
    for (int i = 0; i < locations.length; ++i) mediaPathList.add(Uri.decode(locations[i]));
    mShuffling = prefs.getBoolean("shuffling", false);
    mRepeating = prefs.getInt("repeating", REPEAT_NONE);
    int position = prefs.getInt("position_in_list", Math.max(0, mediaPathList.indexOf(currentMedia)));
    long time = prefs.getLong("position_in_song", -1);
    // load playlist
    loadLocations(mediaPathList, position);
    if (time > 0)
        setTime(time);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("position_in_list", 0);
    editor.putLong("position_in_song", 0);
    Util.commitPreferences(editor);
}

88. CustomDirectories#addCustomDirectory()

Project: VCL-Android
Source File: CustomDirectories.java
View license
public static void addCustomDirectory(String path) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(VLCApplication.getAppContext());
    ArrayList<String> dirs = new ArrayList<String>(Arrays.asList(CustomDirectories.getCustomDirectories()));
    dirs.add(path);
    StringBuilder builder = new StringBuilder();
    builder.append(dirs.remove(0));
    for (String s : dirs) {
        builder.append(":");
        builder.append(s);
    }
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("custom_paths", builder.toString());
    Util.commitPreferences(editor);
}

89. CustomDirectories#removeCustomDirectory()

Project: VCL-Android
Source File: CustomDirectories.java
View license
public static void removeCustomDirectory(String path) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(VLCApplication.getAppContext());
    if (!preferences.getString("custom_paths", "").contains(path))
        return;
    ArrayList<String> dirs = new ArrayList<String>(Arrays.asList(preferences.getString("custom_paths", "").split(":")));
    dirs.remove(path);
    String custom_path;
    if (dirs.size() > 0) {
        StringBuilder builder = new StringBuilder();
        builder.append(dirs.remove(0));
        for (String s : dirs) {
            builder.append(":");
            builder.append(s);
        }
        custom_path = builder.toString();
    } else {
        // don't do unneeded extra work
        custom_path = "";
    }
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("custom_paths", custom_path);
    Util.commitPreferences(editor);
}

90. VLCOptions#setEqualizer()

Project: VCL-Android
Source File: VLCOptions.java
View license
public static void setEqualizer(Context context, MediaPlayer.Equalizer eq, int preset) {
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = pref.edit();
    if (eq != null) {
        editor.putBoolean("equalizer_enabled", true);
        final int bandCount = MediaPlayer.Equalizer.getBandCount();
        final float[] bands = new float[bandCount + 1];
        bands[0] = eq.getPreAmp();
        for (int i = 0; i < bandCount; ++i) {
            bands[i + 1] = eq.getAmp(i);
        }
        Preferences.putFloatArray(editor, "equalizer_values", bands);
        editor.putInt("equalizer_preset", preset);
    } else {
        editor.putBoolean("equalizer_enabled", false);
    }
    Util.commitPreferences(editor);
}

91. MainActivity#onCreate()

View license
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_main);
    final TextView checkItOutOnGitHubTextView = (TextView) this.findViewById(R.id.check_it_out_on_github);
    checkItOutOnGitHubTextView.setMovementMethod(LinkMovementMethod.getInstance());
    checkItOutOnGitHubTextView.setText(Html.fromHtml(this.getString(R.string.check_it_out_on_github)));
    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final TextView bodySizeTextView = (TextView) this.findViewById(R.id.body_size);
    bodySizeTextView.setTextSize(sharedPreferences.getInt("preference_font_size", this.getResources().getInteger(R.integer.font_size_default_value)));
    bodySizeTextView.setText(this.getString(R.string.body_size).concat(" - " + sharedPreferences.getInt("preference_body_size", DEFAULT_BODY_SIZE)));
}

92. MapActivity#registerMapView()

Project: vtm
Source File: MapActivity.java
View license
/**
	 * This method is called once by each MapView during its setup process.
	 * 
	 * @param mapView
	 *            the calling MapView.
	 */
public final void registerMapView(MapView mapView) {
    mMapView = mapView;
    mMap = mapView.map();
    SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES_FILE, MODE_PRIVATE);
    if (containsViewport(sharedPreferences)) {
        // get and set the map position and zoom level
        int latitudeE6 = sharedPreferences.getInt(KEY_LATITUDE, 0);
        int longitudeE6 = sharedPreferences.getInt(KEY_LONGITUDE, 0);
        float scale = sharedPreferences.getFloat(KEY_MAP_SCALE, 1);
        MapPosition mapPosition = new MapPosition();
        mapPosition.setPosition(latitudeE6 / 1E6, longitudeE6 / 1E6);
        mapPosition.setScale(scale);
        mMap.setMapPosition(mapPosition);
    }
}

93. FilePicker#onResume()

Project: vtm
Source File: FilePicker.java
View license
@Override
protected void onResume() {
    super.onResume();
    // restore the current directory
    SharedPreferences preferences = getSharedPreferences(PREFERENCES_FILE, MODE_PRIVATE);
    mDirectory = new File(preferences.getString(CURRENT_DIRECTORY, DEFAULT_DIRECTORY));
    if (!mDirectory.exists() || !mDirectory.canRead()) {
        mDirectory = new File(DEFAULT_DIRECTORY);
    }
    browseToCurrentDirectory();
}

94. NavigationDrawerFragment#onCreate()

View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    api = new WaniKaniApi(getActivity());
    prefMan = new PrefManager(getActivity());
    context = getActivity();
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }
}

95. MovieListFragment#getNumberOfColumns()

Project: Watchlist
Source File: MovieListFragment.java
View license
public int getNumberOfColumns() {
    // Get screen width
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    float widthPx = displayMetrics.widthPixels;
    if (isTablet) {
        widthPx = widthPx / 3;
    }
    // Calculate desired width
    SharedPreferences preferences = context.getSharedPreferences(Watchlist.TABLE_USER, Context.MODE_PRIVATE);
    if (preferences.getInt(Watchlist.VIEW_MODE, Watchlist.VIEW_MODE_GRID) == Watchlist.VIEW_MODE_GRID) {
        float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_card_width);
        int columns = Math.round(widthPx / desiredPx);
        return columns > 2 ? columns : 2;
    } else {
        float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_list_card_width);
        int columns = Math.round(widthPx / desiredPx);
        return columns > 1 ? columns : 1;
    }
}

96. MovieSavedFragment#getNumberOfColumns()

Project: Watchlist
Source File: MovieSavedFragment.java
View license
// Helper methods
public int getNumberOfColumns() {
    // Get screen width
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    float widthPx = displayMetrics.widthPixels;
    if (isTablet) {
        widthPx = widthPx / 3;
    }
    // Calculate desired width
    SharedPreferences preferences = context.getSharedPreferences(Watchlist.TABLE_USER, Context.MODE_PRIVATE);
    if (preferences.getInt(Watchlist.VIEW_MODE, Watchlist.VIEW_MODE_GRID) == Watchlist.VIEW_MODE_GRID) {
        float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_card_width);
        int columns = Math.round(widthPx / desiredPx);
        return columns > 2 ? columns : 2;
    } else {
        float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_list_card_width);
        int columns = Math.round(widthPx / desiredPx);
        return columns > 1 ? columns : 1;
    }
}

97. Util#setTheme()

Project: NetGuard
Source File: Util.java
View license
public static void setTheme(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean dark = prefs.getBoolean("dark_theme", false);
    String theme = prefs.getString("theme", "teal");
    if (theme.equals("teal"))
        context.setTheme(dark ? R.style.AppThemeTealDark : R.style.AppThemeTeal);
    else if (theme.equals("blue"))
        context.setTheme(dark ? R.style.AppThemeBlueDark : R.style.AppThemeBlue);
    else if (theme.equals("purple"))
        context.setTheme(dark ? R.style.AppThemePurpleDark : R.style.AppThemePurple);
    else if (theme.equals("amber"))
        context.setTheme(dark ? R.style.AppThemeAmberDark : R.style.AppThemeAmber);
    else if (theme.equals("orange"))
        context.setTheme(dark ? R.style.AppThemeOrangeDark : R.style.AppThemeOrange);
    else if (theme.equals("green"))
        context.setTheme(dark ? R.style.AppThemeGreenDark : R.style.AppThemeGreen);
}

98. NavigationDrawerFragment#onCreate()

View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mIsThemeLight = SharedPreferencesHelper.isCurrentThemeLight(getActivity());
    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
    if (savedInstanceState != null) {
        //mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }
    // To get call to handle home button
    hasOptionsMenu();
}

99. ActivityHelper#setSelectedLanguage()

Project: NotePad
Source File: ActivityHelper.java
View license
/**
     * Set configured locale on current context
     */
public static void setSelectedLanguage(@NonNull Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Configuration config = context.getResources().getConfiguration();
    String lang = prefs.getString(context.getString(R.string.const_preference_locale_key), "");
    if (!config.locale.toString().equals(lang)) {
        Locale locale;
        if ("".equals(lang))
            locale = Locale.getDefault();
        else if (lang.length() == 5) {
            locale = new Locale(lang.substring(0, 2), lang.substring(3, 5));
        } else {
            locale = new Locale(lang.substring(0, 2));
        }
        // Locale.setDefault(locale);
        config.locale = locale;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
    }
}

100. LocaleHelper#getUserLocale()

Project: NotePad
Source File: LocaleHelper.java
View license
/**
     * @return the users's default or selected locale
     */
public static Locale getUserLocale(Context context) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lang = prefs.getString(context.getString(R.string.const_preference_locale_key), "");
    final Locale locale;
    if (lang == null || lang.isEmpty())
        locale = Locale.getDefault();
    else if (lang.length() == 5) {
        locale = new Locale(lang.substring(0, 2), lang.substring(3, 5));
    } else {
        locale = new Locale(lang.substring(0, 2));
    }
    return locale;
}