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. 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;
}

3. 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);
    }
}

4. 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;
    }
}

5. 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);
}

6. 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);
}

7. 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);
}

8. 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));
    }
}

9. 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, "");
}

10. 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, "");
}

11. 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;
        }
    }
}

12. 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;
        }
    }
}

13. 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();
    }
}

14. 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);
    }
}

15. 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;
}

16. 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;
}

17. 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));
}

18. 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);
}

19. 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");
}

20. 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);
}

21. 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;
}

22. 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();
    }
}

23. 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));
            }
        }
    });
}

24. 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();
        }
    });
}

25. 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);
}

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. 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;
}

28. 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();
    }
}

29. 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));
}

30. 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();
    }
}

31. 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;
    }
}

32. 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();
    }
}

33. 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);
}

34. 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) {
    }
}

35. 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)) {
    }
}

36. 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();
    }
}

37. 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);
}

38. 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();
}

39. 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);
}

40. 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);
    }
}

41. 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();
}

42. 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;
}

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. 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;
}

45. 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));
            }
        }
    }
}

46. 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);
}

47. 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);
}

48. 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);
}

49. 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);
}

50. 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, "");
}

51. 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);
}

52. 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;
}

53. 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);
}

54. 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);
}

55. 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());
        }
    }
}

56. MainActivity#onCreate()

Project: 2048
Source File: MainActivity.java
View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = new MainView(this);
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    view.hasSaveState = settings.getBoolean("save_state", false);
    if (savedInstanceState != null) {
        if (savedInstanceState.getBoolean("hasState")) {
            load();
        }
    }
    setContentView(view);
}

57. Utils#saveInfoBySharedPreferences()

Project: ACDD
Source File: Utils.java
View license
/**
     * save ACDD runtime info to sharedPreference
     **/
public static void saveInfoBySharedPreferences(Application application) {
    Map<String, String> concurrentHashMap = new ConcurrentHashMap<String, String>();
    concurrentHashMap.put(getPackageInfo(application).versionName, "dexopt");
    SharedPreferences sharedPreferences = application.getSharedPreferences(InternalConstant.ACDD_CONFIGURE, Context.MODE_PRIVATE);
    if (sharedPreferences == null) {
        sharedPreferences = application.getSharedPreferences(InternalConstant.ACDD_CONFIGURE, Context.MODE_PRIVATE);
    }
    Editor edit = sharedPreferences.edit();
    for (String key : concurrentHashMap.keySet()) {
        edit.putString(key, concurrentHashMap.get(key));
    }
    edit.commit();
}

58. SharedList#init()

Project: AcDisplay
Source File: SharedList.java
View license
protected void init(@NonNull Context context) {
    mList = new HashMap<>();
    mPlaceholder = new ArrayList<>(3);
    mListeners = new ArrayList<>(6);
    createRecyclableFields();
    // Restore previously saved list.
    SharedPreferences prefs = getSharedPreferences(context);
    final int n = prefs.getInt(KEY_NUMBER, 0);
    for (int i = 0; i < n; i++) {
        if (prefs.getBoolean(KEY_USED_ITEM + i, false)) {
            // Create previously saved object.
            V object = mSaver.get(prefs, i);
            mList.put(object, i);
        } else {
            // This is an empty place which we can re-use
            // later.
            mPlaceholder.add(i);
        }
    }
}

59. ApplicationStartupProcessor#deleteUnsentReportsFromOldAppVersion()

View license
/**
     * Delete any old unsent reports if this is a newer version of the app than when we last started.
     */
public void deleteUnsentReportsFromOldAppVersion() {
    final SharedPreferences prefs = new SharedPreferencesFactory(context, config).create();
    final long lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0);
    final int appVersion = getAppVersion();
    if (appVersion > lastVersionNr) {
        final BulkReportDeleter reportDeleter = new BulkReportDeleter(context);
        reportDeleter.deleteReports(true, 0);
        reportDeleter.deleteReports(false, 0);
        final SharedPreferences.Editor prefsEditor = prefs.edit();
        prefsEditor.putInt(ACRA.PREF_LAST_VERSION_NR, appVersion);
        PrefUtils.save(prefsEditor);
    }
}

60. SmilesRecentsController#loadRecents()

View license
private void loadRecents() {
    SharedPreferences prefs = getPreferences();
    String str = prefs.getString(PREF_RECENTS, "");
    StringTokenizer tokenizer = new StringTokenizer(str, "~");
    while (tokenizer.hasMoreTokens()) {
        try {
            add(Long.valueOf(tokenizer.nextToken()));
        } catch (NumberFormatException e) {
        }
    }
}

61. SmilesRecentsController#saveRecents()

View license
public void saveRecents() {
    StringBuilder str = new StringBuilder();
    int c = size();
    for (int i = 0; i < c; i++) {
        Long e = get(i);
        str.append(e);
        if (i < (c - 1)) {
            str.append('~');
        }
    }
    SharedPreferences prefs = getPreferences();
    prefs.edit().putString(PREF_RECENTS, str.toString()).apply();
}

62. CustomScriptActivity#onCreate()

Project: afwall
Source File: CustomScriptActivity.java
View license
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final View view = getLayoutInflater().inflate(R.layout.customscript, null);
    ((Button) view.findViewById(R.id.customscript_ok)).setOnClickListener(this);
    ((Button) view.findViewById(R.id.customscript_cancel)).setOnClickListener(this);
    ((TextView) view.findViewById(R.id.customscript_link)).setMovementMethod(LinkMovementMethod.getInstance());
    final SharedPreferences prefs = getSharedPreferences(Api.PREFS_NAME, 0);
    this.script = (EditText) view.findViewById(R.id.customscript);
    this.script.setText(prefs.getString(Api.PREF_CUSTOMSCRIPT, ""));
    this.script2 = (EditText) view.findViewById(R.id.customscript2);
    this.script2.setText(prefs.getString(Api.PREF_CUSTOMSCRIPT2, ""));
    setTitle(R.string.set_custom_script);
    setContentView(view);
    Toolbar toolbar = (Toolbar) findViewById(R.id.custom_toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

63. Api#setEnabled()

Project: afwall
Source File: Api.java
View license
/**
	 * Defines if the firewall is enabled and broadcasts the new status
	 * @param ctx mandatory context
	 * @param enabled enabled flag
	 */
public static void setEnabled(Context ctx, boolean enabled, boolean showErrors) {
    if (ctx == null)
        return;
    SharedPreferences prefs = ctx.getSharedPreferences(PREF_FIREWALL_STATUS, Context.MODE_PRIVATE);
    if (prefs.getBoolean(PREF_ENABLED, false) == enabled) {
        return;
    }
    rulesUpToDate = false;
    Editor edit = prefs.edit();
    edit.putBoolean(PREF_ENABLED, enabled);
    if (!edit.commit()) {
        if (showErrors)
            toast(ctx, ctx.getString(R.string.error_write_pref));
        return;
    }
    if (G.activeNotification()) {
        Api.showNotification(Api.isEnabled(ctx), ctx);
    }
    /* notify */
    Intent message = new Intent(Api.STATUS_CHANGED_MSG);
    message.putExtra(Api.STATUS_EXTRA, enabled);
    ctx.sendBroadcast(message);
}

64. NavigationDrawerFragment#onCreate()

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

65. BrowseFragment#updateBackground()

Project: Amphitheatre
Source File: BrowseFragment.java
View license
private void updateBackground(String url) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
    RequestCreator requestCreator = Picasso.with(getActivity()).load(url).placeholder(R.drawable.placeholder).resize(mMetrics.widthPixels, mMetrics.heightPixels).centerCrop().skipMemoryCache();
    switch(Enums.BlurState.valueOf(sharedPrefs.getString(Constants.BACKGROUND_BLUR, ""))) {
        case ON:
            requestCreator = requestCreator.transform(mBlurTransformation);
            break;
    }
    requestCreator.into(mBackgroundTarget);
}

66. Main#isUpdate()

Project: andlytics
Source File: Main.java
View license
/**
	 * checks if the app is started for the first time (after an update).
	 * 
	 * @return <code>true</code> if this is the first start (after an update)
	 * else <code>false</code>
	 */
private boolean isUpdate() {
    // Get the versionCode of the Package, which must be different
    // (incremented) in each release on the market in the
    // AndroidManifest.xml
    final int versionCode = Utils.getActualVersionCode(this);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final long lastVersionCode = prefs.getLong(LAST_VERSION_CODE_KEY, 0);
    // authorization popup from GLS
    if (lastVersionCode == 0) {
        return false;
    }
    if (versionCode != lastVersionCode) {
        Log.i(TAG, "versionCode " + versionCode + " is different from the last known version " + lastVersionCode);
        return true;
    } else {
        Log.i(TAG, "versionCode " + versionCode + " is already known");
        return false;
    }
}

67. Main#showChangelog()

Project: andlytics
Source File: Main.java
View license
private void showChangelog() {
    final int versionCode = Utils.getActualVersionCode(this);
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    ChangelogBuilder.create(this, new Dialog.OnClickListener() {

        public void onClick(DialogInterface dialogInterface, int i) {
            // Mark this version as read
            sp.edit().putLong(LAST_VERSION_CODE_KEY, versionCode).commit();
            dialogInterface.dismiss();
        }
    }).show();
}

68. InstantUploadBroadcastReceiver#getUploadBehaviour()

View license
private Integer getUploadBehaviour(Context context) {
    SharedPreferences appPreferences = android.preference.PreferenceManager.getDefaultSharedPreferences(context);
    String behaviour = appPreferences.getString("prefs_instant_behaviour", "NOTHING");
    if (behaviour.equalsIgnoreCase("NOTHING")) {
        Log_OC.d(TAG, "upload file and do nothing");
        return FileUploader.LOCAL_BEHAVIOUR_FORGET;
    } else if (behaviour.equalsIgnoreCase("MOVE")) {
        Log_OC.d(TAG, "upload file and move file to oc folder");
        return FileUploader.LOCAL_BEHAVIOUR_MOVE;
    }
    return null;
}

69. PassCodeActivity#checkPassCode()

Project: android
Source File: PassCodeActivity.java
View license
/**
     * Compares pass code entered by the user with the value currently saved in the app.
     *
     * @return     'True' if entered pass code equals to the saved one.
     */
protected boolean checkPassCode() {
    SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String savedPassCodeDigits[] = new String[4];
    savedPassCodeDigits[0] = appPrefs.getString(PREFERENCE_PASSCODE_D1, null);
    savedPassCodeDigits[1] = appPrefs.getString(PREFERENCE_PASSCODE_D2, null);
    savedPassCodeDigits[2] = appPrefs.getString(PREFERENCE_PASSCODE_D3, null);
    savedPassCodeDigits[3] = appPrefs.getString(PREFERENCE_PASSCODE_D4, null);
    boolean result = true;
    for (int i = 0; i < mPassCodeDigits.length && result; i++) {
        result = (mPassCodeDigits[i] != null) && mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
    }
    return result;
}

70. CastPreference#onCreate()

View license
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.application_preference);
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mCastManager = VideoCastManager.getInstance();
    /* Volume settings */
    mVolumeListPreference = (ListPreference) getPreferenceScreen().findPreference(VOLUME_SELECTION_KEY);
    String volValue = prefs.getString(VOLUME_SELECTION_KEY, getString(R.string.prefs_volume_default));
    String volSummary = getResources().getString(R.string.prefs_volume_title_summary, volValue);
    mVolumeListPreference.setSummary(volSummary);
    EditTextPreference versionPref = (EditTextPreference) findPreference("app_version");
    versionPref.setTitle(getString(R.string.version, Utils.getAppVersionName(this), getString(R.string.ccl_version)));
}

71. PrefsUtil#toggleFavorite()

Project: android-historian
Source File: PrefsUtil.java
View license
public static boolean toggleFavorite(Context cxt, int productKey) {
    boolean toSet;
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cxt);
    if (isFavorite(cxt, productKey)) {
        toSet = false;
    } else {
        toSet = true;
    }
    final SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(PREFS_KEY_PREFIX + productKey, toSet);
    editor.commit();
    return toSet;
}

72. PrefsUtil#getFavorites()

Project: android-historian
Source File: PrefsUtil.java
View license
//For Favorites, we return verbose product names - which will Show the Staggared Layout Manager
public static ArrayList<String> getFavorites(Context cxt) {
    ArrayList<String> list = new ArrayList<>();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cxt);
    //Clunky I know
    for (int x = 0; x < VersionData.osVersions.length; x++) {
        int productInt = VersionData.osVersions[x];
        if (isFavorite(cxt, productInt)) {
            list.add(VersionData.getProductName(productInt));
            Log.d("PREFS", "Setting a favorite in list: " + VersionData.getProductName(productInt));
        }
    }
    for (int x = 0; x < VersionData.deviceVersions.length; x++) {
        int productInt = VersionData.deviceVersions[x];
        if (isFavorite(cxt, productInt)) {
            list.add(VersionData.getProductName(productInt));
            Log.d("PREFS", "Setting a favorite in list: " + VersionData.getProductName(productInt));
        }
    }
    return list;
}

73. BaseActivity#updateIcon()

View license
private void updateIcon(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(AimsicdService.SHARED_PREFERENCES_BASENAME, 0);
    final String iconType = prefs.getString(context.getString(R.string.pref_ui_icons_key), "SENSE").toUpperCase();
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (getActionBar() != null) {
                getActionBar().setIcon(Icon.getIcon(Icon.Type.valueOf(iconType), ((AndroidIMSICatcherDetector) getApplication()).getStatus()));
            }
        }
    });
}

74. LensRocketService#isUserAuthenticated()

View license
/***************************************************************/
/** Auth Methods **/
/***************************************************************/
/**
	 * Checks to see if we have userId and token stored on the device and sets them if so
	 * @return
	 */
public boolean isUserAuthenticated() {
    SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
    if (settings != null) {
        String userId = settings.getString("userid", null);
        String token = settings.getString("token", null);
        String username = settings.getString("username", null);
        String email = settings.getString("email", null);
        String registrationId = settings.getString("registrationId", null);
        if (userId != null && !userId.equals("")) {
            setUserData(userId, token, username, email, registrationId);
            return true;
        }
    }
    return false;
}

75. PersistentState#onResume()

View license
/**
     * Upon being resumed we can retrieve the current state.  This allows us
     * to update the state if it was changed at any time while paused.
     */
@Override
protected void onResume() {
    super.onResume();
    SharedPreferences prefs = getPreferences(0);
    String restoredText = prefs.getString("text", null);
    if (restoredText != null) {
        mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
        int selectionStart = prefs.getInt("selection-start", -1);
        int selectionEnd = prefs.getInt("selection-end", -1);
        if (selectionStart != -1 && selectionEnd != -1) {
            mSaved.setSelection(selectionStart, selectionEnd);
        }
    }
}

76. RedirectGetter#loadPrefs()

View license
private final void loadPrefs() {
    // Retrieve the current redirect values.
    // NOTE: because this preference is shared between multiple
    // activities, you must be careful about when you read or write
    // it in order to keep from stepping on yourself.
    SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
    mTextPref = preferences.getString("text", null);
    if (mTextPref != null) {
        mText.setText(mTextPref);
    } else {
        mText.setText("");
    }
}

77. RedirectMain#loadPrefs()

View license
private final boolean loadPrefs() {
    // Retrieve the current redirect values.
    // NOTE: because this preference is shared between multiple
    // activities, you must be careful about when you read or write
    // it in order to keep from stepping on yourself.
    SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
    mTextPref = preferences.getString("text", null);
    if (mTextPref != null) {
        TextView text = (TextView) findViewById(R.id.text);
        text.setText(mTextPref);
        return true;
    }
    return false;
}

78. CSCActivity#setUnits()

View license
private void setUnits() {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT)));
    switch(unit) {
        case // [m/s]
        SettingsFragment.SETTINGS_UNIT_M_S:
            mSpeedUnitView.setText(R.string.csc_speed_unit_m_s);
            mDistanceUnitView.setText(R.string.csc_distance_unit_m);
            mTotalDistanceUnitView.setText(R.string.csc_total_distance_unit_km);
            break;
        case // [km/h]
        SettingsFragment.SETTINGS_UNIT_KM_H:
            mSpeedUnitView.setText(R.string.csc_speed_unit_km_h);
            mDistanceUnitView.setText(R.string.csc_distance_unit_m);
            mTotalDistanceUnitView.setText(R.string.csc_total_distance_unit_km);
            break;
        case // [mph]
        SettingsFragment.SETTINGS_UNIT_MPH:
            mSpeedUnitView.setText(R.string.csc_speed_unit_mph);
            mDistanceUnitView.setText(R.string.csc_distance_unit_yd);
            mTotalDistanceUnitView.setText(R.string.csc_total_distance_unit_mile);
            break;
    }
}

79. SettingsFragment#onSharedPreferenceChanged()

View license
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
    final SharedPreferences preferences = getPreferenceManager().getSharedPreferences();
    if (SETTINGS_PACKET_RECEIPT_NOTIFICATION_ENABLED.equals(key)) {
        final boolean disabled = !preferences.getBoolean(SETTINGS_PACKET_RECEIPT_NOTIFICATION_ENABLED, true);
        if (disabled) {
            new AlertDialog.Builder(getActivity()).setMessage(R.string.dfu_settings_dfu_number_of_packets_info).setTitle(R.string.dfu_settings_dfu_information).setPositiveButton(R.string.ok, null).show();
        }
    } else if (SETTINGS_NUMBER_OF_PACKETS.equals(key)) {
        updateNumberOfPacketsSummary();
    } else if (SETTINGS_MBR_SIZE.equals(key)) {
        updateMBRSize();
    } else if (SETTINGS_ASSUME_DFU_NODE.equals(key) && sharedPreferences.getBoolean(key, false)) {
        new AlertDialog.Builder(getActivity()).setMessage(R.string.dfu_settings_dfu_assume_dfu_mode_info).setTitle(R.string.dfu_settings_dfu_information).setPositiveButton(R.string.ok, null).show();
    }
}

80. SettingsFragment#updateNumberOfPacketsSummary()

View license
private void updateNumberOfPacketsSummary() {
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences preferences = getPreferenceManager().getSharedPreferences();
    String value = preferences.getString(SETTINGS_NUMBER_OF_PACKETS, String.valueOf(SETTINGS_NUMBER_OF_PACKETS_DEFAULT));
    // Security check
    if (TextUtils.isEmpty(value)) {
        value = String.valueOf(SETTINGS_NUMBER_OF_PACKETS_DEFAULT);
        preferences.edit().putString(SETTINGS_NUMBER_OF_PACKETS, value).apply();
    }
    screen.findPreference(SETTINGS_NUMBER_OF_PACKETS).setSummary(value);
    final int valueInt = Integer.parseInt(value);
    if (valueInt > 200) {
        new AlertDialog.Builder(getActivity()).setMessage(R.string.dfu_settings_dfu_number_of_packets_info).setTitle(R.string.dfu_settings_dfu_information).setPositiveButton(R.string.ok, null).show();
    }
}

81. HTSActivity#setUnits()

View license
private void setUnits() {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT)));
    switch(unit) {
        case SettingsFragment.SETTINGS_UNIT_C:
            mHTSUnit.setText(R.string.hts_unit_celsius);
            break;
        case SettingsFragment.SETTINGS_UNIT_F:
            mHTSUnit.setText(R.string.hts_unit_fahrenheit);
            break;
        case SettingsFragment.SETTINGS_UNIT_K:
            mHTSUnit.setText(R.string.hts_unit_kelvin);
            break;
    }
    if (mValueC != null)
        setHTSValueOnView(mValueC);
}

82. HTSActivity#setHTSValueOnView()

View license
private void setHTSValueOnView(double value) {
    mValueC = value;
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT)));
    switch(unit) {
        case SettingsFragment.SETTINGS_UNIT_F:
            value = value * 1.8 + 32;
            break;
        case SettingsFragment.SETTINGS_UNIT_K:
            value += 273.15;
            break;
        case SettingsFragment.SETTINGS_UNIT_C:
            break;
    }
    mHTSValue.setText(mFormattedTemp.format(value));
}

83. ProximityActivity#setGUI()

View license
private void setGUI() {
    mFindMeButton = (Button) findViewById(R.id.action_findme);
    mLockImage = (ImageView) findViewById(R.id.imageLock);
    mGattServerSwitch = (CheckBox) findViewById(R.id.option);
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ProximityActivity.this);
    mGattServerSwitch.setChecked(preferences.getBoolean(PREFS_GATT_SERVER_ENABLED, true));
    mGattServerSwitch.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            preferences.edit().putBoolean(PREFS_GATT_SERVER_ENABLED, isChecked).apply();
        }
    });
}

84. RSCActivity#setUnits()

View license
private void setUnits() {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT)));
    switch(unit) {
        case // [m/s]
        SettingsFragment.SETTINGS_UNIT_M_S:
            mSpeedUnitView.setText(R.string.rsc_speed_unit_m_s);
            mDistanceUnitView.setText(R.string.rsc_distance_unit_m);
            mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_km);
            break;
        case // [km/h]
        SettingsFragment.SETTINGS_UNIT_KM_H:
            mSpeedUnitView.setText(R.string.rsc_speed_unit_km_h);
            mDistanceUnitView.setText(R.string.rsc_distance_unit_m);
            mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_km);
            break;
        case // [mph]
        SettingsFragment.SETTINGS_UNIT_MPH:
            mSpeedUnitView.setText(R.string.rsc_speed_unit_mph);
            mDistanceUnitView.setText(R.string.rsc_distance_unit_yd);
            mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_mile);
            break;
    }
}

85. CameraConfigurationManager#setTorch()

View license
void setTorch(Camera camera, boolean newSetting) {
    Camera.Parameters parameters = camera.getParameters();
    doSetTorch(parameters, newSetting);
    camera.setParameters(parameters);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean currentSetting = prefs.getBoolean(PreferencesActivity.KEY_TOGGLE_LIGHT, false);
    if (currentSetting != newSetting) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(PreferencesActivity.KEY_TOGGLE_LIGHT, newSetting);
        editor.commit();
    }
}

86. CameraManager#openDriver()

Project: android-ocr
Source File: CameraManager.java
View license
/**
   * Opens the camera driver and initializes the hardware parameters.
   *
   * @param holder The surface object which the camera will draw preview frames into.
   * @throws IOException Indicates the camera driver failed to open.
   */
public synchronized void openDriver(SurfaceHolder holder) throws IOException {
    Camera theCamera = camera;
    if (theCamera == null) {
        theCamera = Camera.open();
        if (theCamera == null) {
            throw new IOException();
        }
        camera = theCamera;
    }
    camera.setPreviewDisplay(holder);
    if (!initialized) {
        initialized = true;
        configManager.initFromCameraParameters(theCamera);
        if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {
            adjustFramingRect(requestedFramingRectWidth, requestedFramingRectHeight);
            requestedFramingRectWidth = 0;
            requestedFramingRectHeight = 0;
        }
    }
    configManager.setDesiredCameraParameters(theCamera);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    reverseImage = prefs.getBoolean(PreferencesActivity.KEY_REVERSE_IMAGE, false);
}

87. Translator#translate()

Project: android-ocr
Source File: Translator.java
View license
static String translate(Activity activity, String sourceLanguageCode, String targetLanguageCode, String sourceText) {
    // Check preferences to determine which translation API to use--Google, or Bing.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    String api = prefs.getString(PreferencesActivity.KEY_TRANSLATOR, CaptureActivity.DEFAULT_TRANSLATOR);
    // Delegate the translation based on the user's preference.
    if (api.equals(PreferencesActivity.TRANSLATOR_BING)) {
        // Get the correct code for the source language for this translation service.
        sourceLanguageCode = TranslatorBing.toLanguage(LanguageCodeHelper.getTranslationLanguageName(activity.getBaseContext(), sourceLanguageCode));
        return TranslatorBing.translate(sourceLanguageCode, targetLanguageCode, sourceText);
    } else if (api.equals(PreferencesActivity.TRANSLATOR_GOOGLE)) {
        // Get the correct code for the source language for this translation service.
        sourceLanguageCode = TranslatorGoogle.toLanguage(LanguageCodeHelper.getTranslationLanguageName(activity.getBaseContext(), sourceLanguageCode));
        return TranslatorGoogle.translate(sourceLanguageCode, targetLanguageCode, sourceText);
    }
    return BAD_TRANSLATION_MSG;
}

88. NavigationDrawerFragment#onCreate()

View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 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;
    }
    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

89. AutofillService#setAppMatchingPasswords()

View license
private void setAppMatchingPasswords(String appName, String packageName) {
    // if autofill_default is checked and prefs.getString DNE, 'Automatically match with password'/"first" otherwise "never"
    String defValue = settings.getBoolean("autofill_default", true) ? "/first" : "/never";
    SharedPreferences prefs;
    String preference;
    prefs = getSharedPreferences("autofill", Context.MODE_PRIVATE);
    preference = prefs.getString(packageName, defValue);
    switch(preference) {
        case "/first":
            if (!PasswordRepository.isInitialized()) {
                PasswordRepository.initialize(this);
            }
            items = searchPasswords(PasswordRepository.getRepositoryDirectory(this), appName);
            break;
        case "/never":
            items = new ArrayList<>();
            break;
        default:
            getPreferredPasswords(preference);
    }
}

90. pwgen#setPrefs()

Project: Android-Password-Store
Source File: pwgen.java
View license
/**
     * Sets password generation preferences.
     *
     * @param ctx     context from which to retrieve SharedPreferences from
     *                preferences file 'pwgen'
     * @param argv    options for password generation
     *                <table summary="options for password generation">
     *                <tr><td>Option</td><td>Description</td></tr>
     *                <tr><td>0</td><td>don't include numbers</td></tr>
     *                <tr><td>A</td><td>don't include uppercase letters</td></tr>
     *                <tr><td>B</td><td>don't include ambiguous charactersl</td></tr>
     *                <tr><td>s</td><td>generate completely random passwords</td></tr>
     *                <tr><td>v</td><td>don't include vowels</td></tr>
     *                <tr><td>y</td><td>include at least one symbol</td></tr>
     *                </table>
     * @param numArgv numerical options for password generation: length of
     *                generated passwords followed by number of passwords to
     *                generate
     * @return <code>false</code> if a numerical options is invalid,
     * <code>true</code> otherwise
     */
public static boolean setPrefs(Context ctx, ArrayList<String> argv, int... numArgv) {
    SharedPreferences prefs = ctx.getSharedPreferences("pwgen", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    for (char option : pwOptions.toCharArray()) {
        if (argv.contains(String.valueOf(option))) {
            editor.putBoolean(String.valueOf(option), true);
            argv.remove(String.valueOf(option));
        } else {
            editor.putBoolean(String.valueOf(option), false);
        }
    }
    for (int i = 0; i < numArgv.length && i < 2; i++) {
        if (numArgv[i] <= 0) {
            // Invalid password length or number of passwords
            return false;
        }
        String name = i == 0 ? "length" : "num";
        editor.putInt(name, numArgv[i]);
    }
    editor.apply();
    return true;
}

91. PasswordRepository#initialize()

View license
public static Repository initialize(Context context) {
    File dir = getRepositoryDirectory(context);
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    if (dir == null) {
        return null;
    }
    // uninitialize the repo if the dir does not exist or is absolutely empty
    if (!dir.exists() || !dir.isDirectory() || FileUtils.listFiles(dir, null, false).isEmpty()) {
        settings.edit().putBoolean("repository_initialized", false).apply();
    }
    if (!PasswordRepository.getPasswords(dir).isEmpty()) {
        settings.edit().putBoolean("repository_initialized", true).apply();
    }
    // create the repository static variable in PasswordRepository
    return PasswordRepository.getRepository(new File(dir.getAbsolutePath() + "/.git"));
}

92. NavigationDrawerFragment#onCreate()

View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 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;
    }
    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

93. WhatsNewDialog#isToShow()

Project: android-proxy
Source File: WhatsNewDialog.java
View license
public Boolean isToShow() {
    //ToDo check if version is shown
    final SharedPreferences prefs = getContext().getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_MULTI_PROCESS);
    final int versionShown = prefs.getInt(WHATS_NEW_LAST_SHOWN, 0);
    if (versionShown != appInfo.versionCode) {
        //This version is new, show only the changes from this version (if available)
        //Update last shown version
        final SharedPreferences.Editor edit = prefs.edit();
        edit.putInt(WHATS_NEW_LAST_SHOWN, appInfo.versionCode);
        edit.commit();
        return true;
    } else
        return false;
}

94. DeveloperOptionsActivity#listPrefs()

View license
public void listPrefs(View view) {
    TextView textViewTest = new TextView(this);
    testDBContainer.addView(textViewTest);
    textViewTest.setTextSize(10);
    SharedPreferences preferences = this.getSharedPreferences(Constants.PREFERENCES_FILENAME, MODE_MULTI_PROCESS);
    Map<String, ?> prefsMap = preferences.getAll();
    for (String key : prefsMap.keySet()) {
        textViewTest.append("'" + key + "': " + prefsMap.get(key) + "\n");
    }
}

95. NavDrawFragment#onCreate()

Project: android-proxy
Source File: NavDrawFragment.java
View license
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 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;
    }
    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

96. ApplicationStatistics#updateInstallationDetails()

View license
public void updateInstallationDetails() {
    SharedPreferences prefs = context.getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_MULTI_PROCESS);
    SharedPreferences.Editor editor = prefs.edit();
    long launch_count = prefs.getLong(Constants.PREFERENCES_APP_LAUNCH_COUNT, 0) + 1;
    editor.putLong(Constants.PREFERENCES_APP_LAUNCH_COUNT, launch_count);
    long date_firstLaunch = prefs.getLong(Constants.PREFERENCES_APP_DATE_FIRST_LAUNCH, 0);
    if (date_firstLaunch == 0) {
        date_firstLaunch = System.currentTimeMillis();
        editor.putLong(Constants.PREFERENCES_APP_DATE_FIRST_LAUNCH, date_firstLaunch);
    }
    editor.commit();
    getInstallationDetails();
    Timber.i(toString());
}

97. StartupActions#updateStatus()

Project: android-proxy
Source File: StartupActions.java
View license
private static void updateStatus(String actionKey, StartupActionStatus status, String description) {
    SharedPreferences prefs = App.getInstance().getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_MULTI_PROCESS);
    SharedPreferences.Editor editor = prefs.edit();
    if (editor != null) {
        editor.putInt(actionKey, status.getValue());
        editor.commit();
        App.getEventsReporter().sendEvent(App.getInstance().getString(R.string.analytics_cat_startup_action), description, status.toString(), 0L);
    }
}

98. UrlManager#addUsedUrl()

Project: android-proxy
Source File: UrlManager.java
View license
public static void addUsedUrl(Context ctx, String url) {
    SharedPreferences sharedPref = ctx.getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_MULTI_PROCESS);
    String cachedUrls = sharedPref.getString(Constants.PREFERENCES_CACHED_URLS, "");
    SharedPreferences.Editor keyValuesEditor = sharedPref.edit();
    if (cachedUrls == "") {
        keyValuesEditor.putString(Constants.PREFERENCES_CACHED_URLS, url);
        keyValuesEditor.commit();
    } else {
        List<String> urlsList = new ArrayList<String>(Arrays.asList(cachedUrls.split(",")));
        if (!urlsList.contains(url)) {
            cachedUrls = cachedUrls.concat("," + url);
            keyValuesEditor.putString(Constants.PREFERENCES_CACHED_URLS, cachedUrls);
            keyValuesEditor.commit();
        }
    }
}

99. RateThisApp#onStart()

View license
/**
     * Call this API when the launcher activity is launched.<br>
     * It is better to call this API in onStart() of the launcher activity.
     * @param context Context
     */
public static void onStart(Context context) {
    SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    Editor editor = pref.edit();
    // If it is the first launch, save the date in shared preference.
    if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) {
        storeInstallDate(context, editor);
    }
    // Increment launch times
    int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);
    launchTimes++;
    editor.putInt(KEY_LAUNCH_TIMES, launchTimes);
    log("Launch times; " + launchTimes);
    editor.commit();
    mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0));
    mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);
    mOptOut = pref.getBoolean(KEY_OPT_OUT, false);
    mAskLaterDate = new Date(pref.getLong(KEY_ASK_LATER_DATE, 0));
    printStatus(context);
}

100. ClementineService#onCreate()

View license
@Override
public void onCreate() {
    super.onCreate();
    // Get a Wakelock Object
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Clementine");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mUseWakeLock = prefs.getBoolean(SharedPreferencesKeys.SP_WAKE_LOCK, false);
}